-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathReversing-Linkedlist-C++.cpp
More file actions
101 lines (91 loc) · 2.06 KB
/
Reversing-Linkedlist-C++.cpp
File metadata and controls
101 lines (91 loc) · 2.06 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
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 ll long long
using namespace std;
struct node
{
int num;
int var;
node *next;
}*head; //node constructed
void createlist(int n);
void reverse(node **head);
void display();
int main()
{
int n,num,item;
cout<<"Enter the number of nodes: ";
cin>>n;
createlist(n);
cout<<"\nLinked list data: \n";
display();
cout<<"\nAfter reversing\n";
reverse(&head);
display();
return 0;
}
void createlist(int n) //function to create linked list.
{
struct node *newnode, *tmp;
int num, i;
head = (struct node *)malloc(sizeof(struct node));
if(head == NULL)
{
cout<<" Memory can not be allocated";
}
else
{
cout<<"Enter the data for node 1: ";
cin>>num;
head-> num = num;
head-> next = NULL; //Links the address field to NULL
tmp = head;
for(i=2; i<=n; i++)
{
newnode = (struct node *)malloc(sizeof(struct node));
if(newnode == NULL) //If newnode is null no memory cannot be allotted
{
cout<<"Memory can not be allocated";
break;
}
else
{
cout<<"Enter the data for node "<<i<<": "; // Entering data in nodes.
cin>>num;
newnode->num = num;
newnode->next = NULL;
tmp->next = newnode;
tmp = tmp->next;
}
}
}
}
void reverse(node **head) //function to reverse linked list
{
struct node *temp = NULL;
struct node *prev = NULL;
struct node *current = (*head);
while(current != NULL) {
temp = current->next;
current->next = prev;
prev = current;
current = temp;
}
(*head) = prev;
}
void display()//function to display linked list
{
struct node *tmp;
if(head == NULL)
{
cout<<"List is empty";
}
else
{
tmp = head;
while(tmp != NULL)
{
cout<<tmp->num<<" ";
tmp = tmp->next;
}
}
}