Skip to content

Commit ecdadb7

Browse files
committed
Linked List Reversal
1 parent 2eb1f8c commit ecdadb7

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

Linked List/linked_list_reversal.cpp

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
struct Node {
5+
int data;
6+
struct Node* next;
7+
Node(int data)
8+
{
9+
this->data = data;
10+
next = NULL;
11+
}
12+
};
13+
14+
struct LinkedList {
15+
Node* head;
16+
LinkedList()
17+
{
18+
head = NULL;
19+
}
20+
void reverse()
21+
{
22+
Node* current = head;
23+
Node *prev = NULL, *temp = NULL;
24+
while (current != NULL)
25+
{
26+
temp = current->next;
27+
current->next = prev;
28+
prev = current;
29+
current = temp;
30+
}
31+
head = prev;
32+
}
33+
void push(int data)
34+
{
35+
Node* temp = new Node(data);
36+
temp->next = head;
37+
head = temp;
38+
}
39+
void display()
40+
{
41+
struct Node* temp = head;
42+
while (temp != NULL)
43+
{
44+
cout << temp->data << " ";
45+
temp = temp->next;
46+
}
47+
cout<<endl;
48+
}
49+
};
50+
51+
int main()
52+
{
53+
int n, data;
54+
LinkedList ll;
55+
cout<<"Enter the number of elements to be added in Linked List: ";
56+
cin>>n;
57+
for(int i=0;i<n;i++)
58+
{
59+
cout<<"Enter the data item "<<i+1<<": ";
60+
cin>>data;
61+
ll.push(data);
62+
}
63+
cout << "The Linked List is:\n";
64+
ll.display();
65+
cout<<"The Reversed Linked List is:\n";
66+
ll.reverse();
67+
ll.display();
68+
return 0;
69+
}

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@ This is a repository containing various C++ Programs to understand the basic con
2424
C++ Code for implementing a Linked List.
2525

2626

27+
* [Linked List Reversal](https://github.com/altruistcoder/Data-Structures/blob/master/Linked%20List/linked_list_reversal.cpp):
28+
29+
C++ Code for implementing Linked List reversal.
30+
31+
2732
* [Queue Implementation](https://github.com/altruistcoder/Data-Structures/blob/master/Queue/queue.cpp):
2833

2934
C++ Code for implemention of a queue.

0 commit comments

Comments
 (0)