File tree 1 file changed +80
-0
lines changed
1 file changed +80
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ using namespace std ;
3
+
4
+ /* Link list node */
5
+ struct Node {
6
+ int data;
7
+ struct Node * next;
8
+ Node (int data)
9
+ {
10
+ this ->data = data;
11
+ next = NULL ;
12
+ }
13
+ };
14
+
15
+ struct LinkedList {
16
+ Node* head;
17
+ LinkedList ()
18
+ {
19
+ head = NULL ;
20
+ }
21
+
22
+ /* Function to reverse the linked list */
23
+ void reverse ()
24
+ {
25
+ // Initialize current, previous and
26
+ // next pointers
27
+ Node* current = head;
28
+ Node *prev = NULL , *next = NULL ;
29
+
30
+ while (current != NULL ) {
31
+ // Store next
32
+ next = current->next ;
33
+
34
+ // Reverse current node's pointer
35
+ current->next = prev;
36
+
37
+ // Move pointers one position ahead.
38
+ prev = current;
39
+ current = next;
40
+ }
41
+ head = prev;
42
+ }
43
+
44
+ /* Function to print linked list */
45
+ void print ()
46
+ {
47
+ struct Node * temp = head;
48
+ while (temp != NULL ) {
49
+ cout << temp->data << " " ;
50
+ temp = temp->next ;
51
+ }
52
+ }
53
+
54
+ void push (int data)
55
+ {
56
+ Node* temp = new Node (data);
57
+ temp->next = head;
58
+ head = temp;
59
+ }
60
+ };
61
+
62
+ /* Driver program to test above function*/
63
+ int main ()
64
+ {
65
+ /* Start with the empty list */
66
+ LinkedList ll;
67
+ ll.push (20 );
68
+ ll.push (4 );
69
+ ll.push (15 );
70
+ ll.push (85 );
71
+
72
+ cout << " Given linked list\n " ;
73
+ ll.print ();
74
+
75
+ ll.reverse ();
76
+
77
+ cout << " \n Reversed Linked list \n " ;
78
+ ll.print ();
79
+ return 0 ;
80
+ }
You can’t perform that action at this time.
0 commit comments