CIRCULAR LINKED LIST
Traverse in a Circular LinkedList
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct node{
int data;
node *next;
};
void printmyList(node *first){
node *temp = first;//copy banay
if(temp!=NULL){
cout<<temp->data<<endl;;
temp=temp->next;
//agar direct while likhega toh temp == first hoga aur while false hoga
while(temp!=first){
cout<<temp->data<<endl;
temp = temp->next;
}
}
}
int main()
{
node *head = new node();
node *second = new node();
node *third = new node();
head->data = 100;
head->next = second;
second->data = 3;
second->next = third;
third->data = 90;
third->next = head;
printmyList(second);
return 0;
}
![]() |
Doubly LL'
insertion or pushing at front
#include <iostream>
using namespace std;
struct node{
int data;
node *next;
node *prev;
};
void push(node **head_ref,int newData){
node *newNode = new node();
newNode->data = newData;
newNode->next = *head_ref;
newNode->prev = NULL;
if(*head_ref !=NULL){
(*head_ref)->prev = newNode;
}
*head_ref = newNode;
}
void print(node *head){
while(head !=NULL){
cout<<head->data;
head = head->next;
}
}
int main()
{
node *head = NULL;
push(&head,68);
push(&head,68);
print(head);
return 0;
}
Insertion of node at end
using namespace std;
struct node{
int data;
node *next;
node *prev;
};
void push(node **head_ref,int newData){
node *newNode = new node();
newNode->data = newData;
newNode->next = *head_ref;
newNode->prev = NULL;
if(*head_ref !=NULL){
(*head_ref)->prev = newNode;
}
*head_ref = newNode;
}
void insertAtEnd(node **head_ref,int newData){
node *newNode = new node();
newNode->data = newData;
newNode->next = NULL;
node *last = *head_ref;
if(*head_ref ==NULL){
newNode->prev = NULL;
*head_ref = newNode;
}
while(last->next != NULL){
last = last->next;
}
last->next = newNode;
newNode->prev = last;
}
void print(node *head){
while(head !=NULL){
cout<<head->data;
head = head->next;
}
}
int main()
{
node *head = NULL;
push(&head,68);
push(&head,68);
insertAtEnd(&head,90);
print(head);
return 0;
}

Comments
Post a Comment