#include <iostream>
using namespace std;
struct List {
int item;
struct List* nextNode;
List(int data)
{
this->item = data;
nextNode = NULL;
}
};
struct LinkedList {
List* head;
LinkedList() { head = NULL; }
void reverseList()
{
List* current = head;
List *prev = NULL, *next = NULL;
while (current != NULL) {
next = current->nextNode;
current->nextNode= prev;
prev = current;
current = next;
}
head = prev;
}
void printList()
{
struct List* temp = head;
while (temp != NULL) {
cout << temp->item << " ";
temp = temp->nextNode;
}
}
void push(int data)
{
List* temp = new List(data);
temp->nextNode = head;
head = temp;
}
};
//Testing code
int main()
{
LinkedList list;
list.push(10);
list.push(20);
list.push(30);
list.push(40);
list.push(50);
cout << "Before reversing the linked list\n";
list.printList();
list.reverseList();
cout << "\nAfter reversing the Linked list \n";
list.printList();
return 0;
}
Comments
Leave a comment