Skip to content

Commit

Permalink
Merge pull request #83 from harshchan/master
Browse files Browse the repository at this point in the history
Create reverseSLL.cpp
  • Loading branch information
manishbisht authored Oct 22, 2021
2 parents 97c6855 + 19fecff commit d6fb189
Showing 1 changed file with 78 additions and 0 deletions.
78 changes: 78 additions & 0 deletions Data Structures/04 Linked List/reverseSLL.cpp
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;
}

0 comments on commit d6fb189

Please sign in to comment.