forked from theutpal01/HacktoberFest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse linked list.cpp
58 lines (54 loc) · 978 Bytes
/
reverse linked list.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
#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
};
void insert(node **head, int data)
{
node *newnode = (node *)malloc(1 * sizeof(node));
newnode->data = data;
newnode->next = NULL;
if ((*head) == NULL)
{
(*head) = newnode;
return;
}
node *temp = (*head);
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = newnode;
}
void reverselinked(node *head)
{
node *prev = NULL;
node *current = head;
while (current != NULL)
{
node *nextnode = current->next;
current->next = prev;
prev = current;
current = nextnode;
}
node *ptr = prev;
while (ptr != NULL)
{
cout << ptr->data << "->";
ptr = ptr->next;
}
}
int main()
{
node *start = NULL;
int n, data;
cin >> n;
while (n--)
{
cin >> data;
insert(&start, data);
}
reverselinked(start);
}