Reverse Linked List

mail@pastecode.io avatar
unknown
plain_text
13 days ago
1.6 kB
1
Indexable
Never
#include <iostream>

using namespace std;

struct node {
	int data;
	struct node *link; //self referencing
};

class LinkedList {
	struct node *head; //pointer to the first node

	public:
	//initalise empty linked list
		LinkedList(){
			head = NULL;
		}

	void insert(int data){
		//Create a new node
		struct node *temp = new node;
		//Set data to new node
		temp->data = data;
		temp->link = NULL;
		//Check if head is null
		if (head==NULL){
			//Set new node as head
			head = temp;
		}
		else{
			struct node *current = head;
			//Go to the end of the list
			while(current->link != NULL){
				current = current->link;
			}
			//Set new node as the last node
			current->link = temp;
		}
		
	}

	void display(){
		struct node *current = head;
		//Traverse the list
		while(current != NULL){
			//Print the data
			cout << current->data << " ";
			//Move to next node
			current = current->link;
		}
		cout << endl;
	}

	void reverse(){
		struct node *prev = NULL;
		struct node *current = head;
		struct node *next = NULL;
		//Traverse the list
		while(current != NULL){
			//Store the next node
			next = current->link;
			//Reverse the link
			current->link = prev;
			//Move to next node
			prev = current;
			current = next;
		}
		//Set the last node as head
		head = prev;
	}
};

int main(){
	cout << "linked lists" << endl;
	LinkedList list;
	list.insert(1);
	list.insert(2);
	list.insert(3);

	list.display();
	list.reverse();
	list.display();
	return 0;
}
Leave a Comment