Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 19fecff

Browse files
Create reverseSLL.cpp
1 parent 97c6855 commit 19fecff

File tree

1 file changed

+78
-0
lines changed

1 file changed

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

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /