-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverseALinkedlist.cpp
More file actions
68 lines (65 loc) · 1.41 KB
/
reverseALinkedlist.cpp
File metadata and controls
68 lines (65 loc) · 1.41 KB
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
#include <iostream>
using namespace std;
class node
{
public:
int data;
node *next = NULL;
};
node *insertAtend(node *head, int data)
{
node *p = new node; // default constructor will be called
p->data = data;
if (!head)
{
head = p; // If the list is empty, the new node becomes the head
return head;
}
// Now if the list is not empty
node *ptr = head;
while (ptr->next)
{
ptr = ptr->next;
}
ptr->next = p;
return head;
}
void traverse(node *head) // This will traverse the the list and print it
{
while (head)
{
cout << head->data << endl;
head = head->next;
}
}
node *reverse(node *head)
{
node *pre = NULL;
node *curr = head;
node *forward = NULL;
while (curr->next != NULL)
{
// breaking the link and again joining it in the new direction
forward = curr->next;
curr->next = pre;
pre = curr;
curr = forward;
}
return pre;
}
int main()
{
node *head = NULL;
head = insertAtend(head, 45);
head = insertAtend(head, 6);
head = insertAtend(head, 8);
head = insertAtend(head, 9);
head = insertAtend(head, 54);
head = insertAtend(head, 99);
head = insertAtend(head, 89);
traverse(head);
cout << endl;
head = reverse(head);
traverse(head);
return 0;
}