-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedlist_1
More file actions
65 lines (57 loc) · 1.34 KB
/
linkedlist_1
File metadata and controls
65 lines (57 loc) · 1.34 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
Write a C++ program to create a singly linked list of n nodes and display it in reverse order.
#include <iostream>
using namespace std;
//Declare node
struct node{
int num;
node *next;
};
//Starting (Head) node
struct node *head=NULL;
//Insert node at start
void insert_Node(int n){
struct node *new_node=new node;
new_node->num=n;
new_node->next=head;
head=new_node;
}
void reverse()
{
// Set the current, previous, and next pointers to their initial values
node* current = head;
node *prev = NULL, *next = NULL;
while (current != NULL) {
// Store next
next = current->next;
// Reverse the node pointer for the current node
current->next = prev;
// Advance the pointer one position.
prev = current;
current = next;
}
head = prev;
}
//Display all nodes
void display_all_nodes()
{
struct node *temp = head;
while(temp!=NULL){
cout<<temp->num<<" ";
temp=temp->next;
}
cout<<endl;
}
int main(){
insert_Node(1);
insert_Node(3);
insert_Node(5);
insert_Node(7);
insert_Node(9);
insert_Node(11);
cout<<"Original Linked list:\n";
display_all_nodes();
cout<<"\nReverse Linked list:\n";
reverse();
display_all_nodes();
return 0;
}