Untitled
unknown
plain_text
a year ago
1.6 kB
9
Indexable
#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;
}
Editor is loading...
Leave a Comment