forked from ashvish183/Hactoberfest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedListReversal.cpp
79 lines (63 loc) · 1.57 KB
/
LinkedListReversal.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
#include<iostream>
#include<cstdlib>
using namespace std;
struct Node
{
int data;
struct Node *next;
};
void LinkedListTraversal(struct Node *ptr)
{
while(ptr != NULL)
{
cout<<"Element : "<<ptr->data<<endl;
ptr = ptr->next;
}
}
// LINKED LIST REVERSAL
struct Node * Linked_List_Reversal(struct Node *head)
{
struct Node *current = head;
struct Node *previous = NULL;
while(current != NULL)
{
struct Node *temp = current->next;
current->next = previous;
previous = current;
current = temp;
}
return previous;
}
int main()
{
struct Node *head;
struct Node *second;
struct Node *third;
struct Node *forth;
struct Node *fifth;
struct Node *sixth;
head = (struct Node *)malloc(sizeof(struct Node));
second = (struct Node *)malloc(sizeof(struct Node));
third = (struct Node *)malloc(sizeof(struct Node));
forth = (struct Node *)malloc(sizeof(struct Node));
fifth = (struct Node *)malloc(sizeof(struct Node));
sixth = (struct Node *)malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 3;
second->next = third;
third->data = 6;
third->next = forth;
forth->data = 88;
forth->next = fifth;
fifth->data = 22;
fifth->next = sixth;
sixth->data = 99;
sixth->next = NULL;
cout<<"Linked List before Reversal : "<<endl;
LinkedListTraversal(head);
head = Linked_List_Reversal(head);
cout<<"Linked List after Reversal : "<<endl;
LinkedListTraversal(head);
return 0;
}