-
Notifications
You must be signed in to change notification settings - Fork 384
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #83 from harshchan/master
Create reverseSLL.cpp
- Loading branch information
Showing
1 changed file
with
78 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
// Iterative C++ program to reverse | ||
// a linked list | ||
#include <iostream> | ||
using namespace std; | ||
|
||
/* Link list node */ | ||
struct Node { | ||
int data; | ||
struct Node* next; | ||
Node(int data) | ||
{ | ||
this->data = data; | ||
next = NULL; | ||
} | ||
}; | ||
|
||
struct LinkedList { | ||
Node* head; | ||
LinkedList() { head = NULL; } | ||
|
||
/* Function to reverse the linked list */ | ||
void reverse() | ||
{ | ||
// Initialize current, previous and | ||
// next pointers | ||
Node* current = head; | ||
Node *prev = NULL, *next = NULL; | ||
|
||
while (current != NULL) { | ||
// Store next | ||
next = current->next; | ||
|
||
// Reverse current node's pointer | ||
current->next = prev; | ||
|
||
// Move pointers one position ahead. | ||
prev = current; | ||
current = next; | ||
} | ||
head = prev; | ||
} | ||
|
||
/* Function to print linked list */ | ||
void print() | ||
{ | ||
struct Node* temp = head; | ||
while (temp != NULL) { | ||
cout << temp->data << " "; | ||
temp = temp->next; | ||
} | ||
} | ||
|
||
void push(int data) | ||
{ | ||
Node* temp = new Node(data); | ||
temp->next = head; | ||
head = temp; | ||
} | ||
}; | ||
|
||
int main() | ||
{ | ||
/* Start with the empty list */ | ||
LinkedList ll; | ||
ll.push(20); | ||
ll.push(4); | ||
ll.push(15); | ||
ll.push(85); | ||
|
||
cout << "Given linked list\n"; | ||
ll.print(); | ||
|
||
ll.reverse(); | ||
|
||
cout << "\nReversed Linked list \n"; | ||
ll.print(); | ||
return 0; | ||
} |