-
Notifications
You must be signed in to change notification settings - Fork 2
/
reverse_linkedlist.cpp
58 lines (50 loc) · 1 KB
/
reverse_linkedlist.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;
class node{
public:
int data;
node* next;
};
void push(node** h_ref,int data ){
node * new_node = new node();
new_node->data = data;
new_node->next = *h_ref;
*h_ref = new_node;
}
void print(node* head){
while(head){
cout<<head->data<<"->";
head=head->next;
}
}
void reverse(node** head)
{
node* current = *head;
node *prev = NULL, *next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head = prev;
}
int main()
{
node* head= NULL;
node* head2= NULL;
push(&head,3);
push(&head,2);
push(&head,5);
push(&head,6);
push(&head,7);
push(&head,8);
push(&head,4);
cout<<"before reverse"<<endl;
print(head);
cout<<endl;
cout<<"after reverse"<<endl;
reverse(&head);
print(head);
return 0;
}