-
Notifications
You must be signed in to change notification settings - Fork 29
/
reverse_Linkedlist.cpp
83 lines (67 loc) · 1.57 KB
/
reverse_Linkedlist.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include<bits/stdc++.h>
using namespace std;
typedef struct Node{
int data;
struct Node*next;
}Node;
Node* insert(Node*head ,int x ) //function to insert node in ll
{
//New node to be inserted
Node * p = new Node;
p->data = x;
p->next = NULL;
//if it's first node
if(head == NULL)
{
head = p;
}
//if head node is there
else{
Node*temp = head;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next = p;
}
return head;
}
Node* reverse(Node*head) //function to reverse
{
// Initialize current, previous and
// next pointers
Node* current = head;
Node *prev = NULL, *next = NULL;
while (current != NULL) {
// Store next
next = current->next;
// Reverse current node's pointer
current->next = prev;
// Move pointers one position ahead.
prev = current;
current = next;
}
head = prev;
return head;
}
void print(Node*head)
{
Node*temp = head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}
int main()
{
Node * head = NULL; //initilaise head to NULL
head = insert(head,1);
head = insert(head,2);
head = insert(head,3);
print(head);
head = reverse(head); //reverse linked list
print(head);
return 0;
}
// Time Complexity: O(n)