-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverseALinkedlist.cpp
101 lines (74 loc) · 2.01 KB
/
reverseALinkedlist.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <bits/stdc++.h>
#define st struct stu
using namespace std;
struct stu
{
int roll;
int marks;
struct stu *next = NULL;
};
int main()
{
struct stu *start=NULL, *newNode, *currNode=NULL;
char p='y';
int i=1;
//create
while(p == 'y' || p == 'Y')
{
printf("Enter node %d\n",i++);
newNode=(struct stu*)malloc(sizeof(struct stu));
scanf("%d%d", &newNode->roll, &newNode->marks);
if(start==NULL)
{
start=newNode;
}
else
{
currNode->next=newNode;
}
currNode=newNode;
printf("Do you wanna add more nodes?(Y/N)");
fflush(stdin);
cin>>p;
}
printf("\n");
//display
struct stu *latestNode=NULL;
latestNode = start;
do
{
printf("Roll no %d got %d marks\n", latestNode->roll, latestNode->marks);
latestNode = latestNode->next;
}while(latestNode->next != NULL);
if (latestNode->next == NULL)
{
printf("Roll no %d got %d marks\n", latestNode->roll, latestNode->marks);
}
//reversal
st *pre = start, *post = start, *curr = start; //curr stands for currentNode
while(curr!=NULL)
{
post = curr->next;
if(curr == start)
curr->next = NULL;
else
curr->next = pre;
pre = curr;
curr = post;
start = pre; //**we change the start here so that we do not need another variable
} //**remember not to use this further in the code for any other purpose
//display the reversed linkedList
printf("\n\nThe reversed linkedList is:\n\n");
latestNode=NULL;
latestNode = start;
do
{
printf("Roll no %d got %d marks\n", latestNode->roll, latestNode->marks);
latestNode = latestNode->next;
}while(latestNode->next != NULL);
if (latestNode->next == NULL)
{
printf("Roll no %d got %d marks\n", latestNode->roll, latestNode->marks);
}
return 0;
}