Skip to content

Commit 876595e

Browse files
authored
Merge pull request #187 from Khushi-74/coding
Reverse linked-list code resolved#150
2 parents 9c8a50d + 5ea2f96 commit 876595e

File tree

2 files changed

+76
-1
lines changed

2 files changed

+76
-1
lines changed

Coding/reverse linked list

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
// Iterative C++ program to reverse a linked list
2+
#include <bits/stdc++.h>
3+
using namespace std;
4+
5+
/* Link list node */
6+
struct Node {
7+
int data;
8+
struct Node* next;
9+
Node(int data)
10+
{
11+
this->data = data;
12+
next = NULL;
13+
}
14+
};
15+
16+
struct LinkedList {
17+
Node* head;
18+
LinkedList() { head = NULL; }
19+
20+
/* Function to reverse the linked list */
21+
void reverse()
22+
{
23+
// Initialize current, previous and next pointers
24+
Node* current = head;
25+
Node *prev = NULL, *next = NULL;
26+
27+
while (current != NULL) {
28+
// Store next
29+
next = current->next;
30+
// Reverse current node's pointer
31+
current->next = prev;
32+
// Move pointers one position ahead.
33+
prev = current;
34+
current = next;
35+
}
36+
head = prev;
37+
}
38+
39+
/* Function to print linked list */
40+
void print()
41+
{
42+
struct Node* temp = head;
43+
while (temp != NULL) {
44+
cout << temp->data << " ";
45+
temp = temp->next;
46+
}
47+
}
48+
49+
void push(int data)
50+
{
51+
Node* temp = new Node(data);
52+
temp->next = head;
53+
head = temp;
54+
}
55+
};
56+
57+
/* Driver code*/
58+
int main()
59+
{
60+
/* Start with the empty list */
61+
LinkedList ll;
62+
ll.push(20);
63+
ll.push(4);
64+
ll.push(15);
65+
ll.push(85);
66+
67+
cout << "Given linked list\n";
68+
ll.print();
69+
70+
ll.reverse();
71+
72+
cout << "\nReversed linked list \n";
73+
ll.print();
74+
return 0;
75+
}
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
Date: 16/11/2022
22
Time: 23:14
3-
Phone Number: +917903530298
3+
Phone Number: +91xxxxxxxx
44
Message: hey
55
--------------------

0 commit comments

Comments
 (0)