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