SlideShare une entreprise Scribd logo
1  sur  13
4. Example Programs
Compile these C++programsand figure outwhatthe outputis andwhyis it appearedlike that.
4.1 Example Program 1: Add/Insertnode infront / at the beginningof a linkedlist
#include <cstdlib>
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
Node* head;
void Insert(int x)
{
Node* temp = new Node();
temp->data = x;
temp->next = head;
head = temp;
}
void Print()
{
Node* temp = head;
cout<<"List is : ";
while(temp!=NULL)
{
cout<<temp->data<<"t";
temp=temp->next;
}
cout<<endl;
}
int main()
{
head=NULL;
cout<<"How many no?n";
int n,i,x;
cin>>n;
for(i=0;i<n;i++)
{
cout<<"Enter no: n";
cin>>x;
Insert(x);
Print();
}
}
Output:
Comment:
Thisprogram receivesuserinputandliststheminorderof newestfirstbyreplacingthe mostrecent
inputwithlatestinputanddisplayingthem
4.2 Example Program 2 : Add/Insert node at nth positionin the linkedlist.
#include <cstdlib>
#include <iostream>
using namespace std;
// A linked list Node
struct Node {
int data;
struct Node* next;
};
// Size of linked list
int size = 0;
// function to create and return a Node
Node* getNode(int data)
{
// allocating space
Node* newNode = new Node();
// inserting the required data
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// function to insert a Node at required position
void insertPos(Node** current, int pos, int data)
{
// This condition to check whether the
// position given is valid or not.
if (pos < 1 || pos > size + 1)
cout << "Invalid position!" << endl;
else {
// Keep looping until the pos is zero
while (pos--) {
if (pos == 0) {
// adding Node at required position
Node* temp = getNode(data);
// Making the new Node to point to
// the old Node at the same position
temp->next = *current;
// Changing the pointer of the Node previous
// to the old Node to point to the new Node
*current = temp;
}
else
// Assign double pointer variable to point to the
// pointer pointing to the address of next Node
current = &(*current)->next;
}
size++;
}
}
// This function prints contents
// of the linked list
void printList(struct Node* head)
{
while (head != NULL) {
cout << " " << head->data;
head = head->next;
}
cout << endl;
}
// Driver Code
int main()
{
// Creating the list 3->5->8->10
Node* head = NULL;
head = getNode(3);
head->next = getNode(5);
head->next->next = getNode(8);
head->next->next->next = getNode(10);
size = 4;
cout << "Linked list before insertion: ";
printList(head);
int data = 12, pos = 3;
insertPos(&head, pos, data);
cout << "Linked list after first insertion is: ";
printList(head);
// front of the linked list
data = 1, pos = 1;
insertPos(&head, pos, data);
cout << "Linked list after second insertion is: ";
printList(head);
// insertion at end of the linked list
data = 15, pos = 7;
insertPos(&head, pos, data);
cout << "Linked list after third insertion is: ";
printList(head);
return 0;
}
Output:
Comment:
ThisProgram insertsanumberintoa premade listat a specificposition(1st
,3rd
,7th
) usingspecificvalues
to representthem(dataandpos)
4.3 Example Program 3 : Delete node at nth positioninthe linked list
#include <cstdlib>
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
Node* head;
void Insert(int x)
{
Node* temp = new Node();
temp->data = x;
temp->next = head;
head = temp;
}
//temp1 points to (n-1)th node
void Delete (int n)
{
Node* temp1=head;
if(n==1)
{
head=temp1->next;
free(temp1);
return;
}
int i;
for(i=0;i<n-2;i++)
{
temp1=temp1->next;
}
Node* temp2=temp1->next;
temp1->next=temp2->next;
free(temp2);
}
void Print()
{
Node* temp = head;
cout<<"Linked List is : ";
while(temp!=NULL)
{
cout<<temp->data<<"t";
temp=temp->next;
}
cout<<endl;
}
int main()
{
head=NULL;
Insert(24);
Insert(38);
Insert(14);
Insert(59);
Print();
Delete(2);
Print();
}
Output:
Comment:
Thisprogram deletesanumberfroma predeterminedlinkedlistusingvoid(Delete) call
4.4 Example Program 4 : Reverse a linkedlist.
#include <cstdlib>
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
Node* Insert(Node* head,int x)
{
Node* temp = new Node();
temp->data = x;
temp->next = head;
head = temp;
return head;
}
Node* Reverse (Node* head)
{
Node *c,*p,*n;
c=head;
p=NULL;
while(c!=NULL)
{
n=c->next;
c->next=p;
p=c;
c=n;
}
head=p;
return head;
}
void Print(Node* head)
{
cout<<"Linked List is : ";
while(head!=NULL)
{
cout<<head->data<<"t";
head=head->next;
}
cout<<endl;
}
int main()
{
Node* head=NULL;
head=Insert(head,2);
head=Insert(head,3);
head=Insert(head,4);
head=Insert(head,5);
Print(head);
head=Reverse(head);
Print(head);
}
Output:
Comment:
Thisprogram reversesthe orderof a predeterminedlinkedlistthrough head=Reverse(head) command
thisrearrangesthe “head”or order of numberpositionsstartingfromlasttofirst
4.5 Example Program 5 : Print a linkedListForward and Backward using recursion.
#include <cstdlib>
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
Node* Insert(Node* head,int data)
{
Node* temp = new Node();
temp->data = data;
temp->next = NULL;
if (head==NULL)head=temp;
else
{
Node* temp1=head;
while (temp1->next != NULL) temp1=temp1->next;
temp1->next=temp;
}
return head;
}
void Print(Node* p)
{
if(p==NULL) return; //exit condition
cout<<p->data<<" "; //print data in node
Print(p->next); //recursive function
}
void ReversePrint (Node* p)
{
if(p==NULL) return;
ReversePrint(p->next);
cout<<p->data<<" ";
}
int main()
{
Node* head=NULL;
head=Insert(head,2);
head=Insert(head,3);
head=Insert(head,4);
head=Insert(head,5);
cout<<"nPrint forward : ";
Print(head);
cout<<"nnPrint Reverse/Backward : ";
ReversePrint(head);
cout<<endl<<endl;
}
Output:
Comment:
Thisprogram issimilartoExample program4.4 whereasthe linkedlistisprinted,reversed,andprinted
againto displaythe listinitsinitial andreversedform
4.6 Example Program 6 : Implementationdoublylinkedlist– to print forward and backward
#include <cstdlib>
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;
Node* prev;
};
Node* head;
Node* GetNewNode(int x)
{
Node* newNode = new Node();
newNode->data=x;
newNode->next=NULL;
newNode->prev=NULL;
return newNode;
}
void InsertAtHead(int x)
{
Node* newNode = GetNewNode(x);
if(head==NULL)
{
head=newNode;
return;
}
head->prev=newNode;
newNode->next=head;
head=newNode;
}
void Print()
{
Node* temp = head;
cout<<"Forward: ";
while(temp!=NULL)
{
cout<<temp->data<<"t";
temp=temp->next;
}
cout<<endl;
}
void ReversePrint()
{
Node* temp = head;
if(temp==NULL)return;
while(temp->next!=NULL)
{
temp=temp->next;
}
cout<<"Reverse: ";
while(temp!=NULL)
{
cout<<temp->data<<"t";
temp=temp->prev;
}
cout<<endl;
}
int main()
{
head=NULL;
InsertAtHead(22);
InsertAtHead(71);
Print();
ReversePrint();
InsertAtHead(38);
InsertAtHead(53);
InsertAtHead(75);
Print();
ReversePrint();
}
Output:
Comment:
Thisprogram isa combinationof Example program4.4and 4.5 but utilizestwolinkedlistsbyadding
another3 nodesafterthe initial forwardandreverse display

Contenu connexe

Similaire à Implement Doubly Linked List

Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdfAssignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdffortmdu
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYMalikireddy Bramhananda Reddy
 
How do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdfHow do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdffeelinggift
 
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdfDoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdfaathiauto
 
#includeiostream struct node {    char value;    struct no.pdf
#includeiostream struct node {    char value;    struct no.pdf#includeiostream struct node {    char value;    struct no.pdf
#includeiostream struct node {    char value;    struct no.pdfankitmobileshop235
 
C++Write a method Node Nodereverse() which reverses a list..pdf
C++Write a method Node Nodereverse() which reverses a list..pdfC++Write a method Node Nodereverse() which reverses a list..pdf
C++Write a method Node Nodereverse() which reverses a list..pdfarjunenterprises1978
 
C program to insert a node in doubly linked list
C program to insert a node in doubly linked listC program to insert a node in doubly linked list
C program to insert a node in doubly linked listSourav Gayen
 
#include stdafx.h #include iostream using namespace std;vo.docx
#include stdafx.h #include iostream using namespace std;vo.docx#include stdafx.h #include iostream using namespace std;vo.docx
#include stdafx.h #include iostream using namespace std;vo.docxajoy21
 
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdfC++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdfpoblettesedanoree498
 
Consider L = {a^nb^2nc^P p 0}. Prove L is not a context-free langu.pdf
Consider L = {a^nb^2nc^P  p  0}. Prove L is not a context-free langu.pdfConsider L = {a^nb^2nc^P  p  0}. Prove L is not a context-free langu.pdf
Consider L = {a^nb^2nc^P p 0}. Prove L is not a context-free langu.pdfbharatchawla141
 
Please find the answer to the above problem as follows- Program.pdf
Please find the answer to the above problem as follows- Program.pdfPlease find the answer to the above problem as follows- Program.pdf
Please find the answer to the above problem as follows- Program.pdfangelfragranc
 
Solution#includestdio.h#includeconio.h#includealloc.h.pdf
Solution#includestdio.h#includeconio.h#includealloc.h.pdfSolution#includestdio.h#includeconio.h#includealloc.h.pdf
Solution#includestdio.h#includeconio.h#includealloc.h.pdfpoddaranand1
 
In C++ I need help with this method that Im trying to write fillLi.pdf
In C++ I need help with this method that Im trying to write fillLi.pdfIn C++ I need help with this method that Im trying to write fillLi.pdf
In C++ I need help with this method that Im trying to write fillLi.pdffantoosh1
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfEricvtJFraserr
 
Doublylinklist
DoublylinklistDoublylinklist
Doublylinklistritu1806
 
Code#include stdio.h #includemalloc.h struct node {  .pdf
Code#include stdio.h #includemalloc.h struct node {  .pdfCode#include stdio.h #includemalloc.h struct node {  .pdf
Code#include stdio.h #includemalloc.h struct node {  .pdfbrijmote
 
data structure3.pptx
data structure3.pptxdata structure3.pptx
data structure3.pptxSajalFayyaz
 

Similaire à Implement Doubly Linked List (20)

Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdfAssignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
 
How do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdfHow do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdf
 
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdfDoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
 
#includeiostream struct node {    char value;    struct no.pdf
#includeiostream struct node {    char value;    struct no.pdf#includeiostream struct node {    char value;    struct no.pdf
#includeiostream struct node {    char value;    struct no.pdf
 
137 Lab-2.2.pdf
137 Lab-2.2.pdf137 Lab-2.2.pdf
137 Lab-2.2.pdf
 
Lab-2.2 717822E504.pdf
Lab-2.2 717822E504.pdfLab-2.2 717822E504.pdf
Lab-2.2 717822E504.pdf
 
C++Write a method Node Nodereverse() which reverses a list..pdf
C++Write a method Node Nodereverse() which reverses a list..pdfC++Write a method Node Nodereverse() which reverses a list..pdf
C++Write a method Node Nodereverse() which reverses a list..pdf
 
C program to insert a node in doubly linked list
C program to insert a node in doubly linked listC program to insert a node in doubly linked list
C program to insert a node in doubly linked list
 
#include stdafx.h #include iostream using namespace std;vo.docx
#include stdafx.h #include iostream using namespace std;vo.docx#include stdafx.h #include iostream using namespace std;vo.docx
#include stdafx.h #include iostream using namespace std;vo.docx
 
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdfC++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
 
Consider L = {a^nb^2nc^P p 0}. Prove L is not a context-free langu.pdf
Consider L = {a^nb^2nc^P  p  0}. Prove L is not a context-free langu.pdfConsider L = {a^nb^2nc^P  p  0}. Prove L is not a context-free langu.pdf
Consider L = {a^nb^2nc^P p 0}. Prove L is not a context-free langu.pdf
 
Please find the answer to the above problem as follows- Program.pdf
Please find the answer to the above problem as follows- Program.pdfPlease find the answer to the above problem as follows- Program.pdf
Please find the answer to the above problem as follows- Program.pdf
 
Solution#includestdio.h#includeconio.h#includealloc.h.pdf
Solution#includestdio.h#includeconio.h#includealloc.h.pdfSolution#includestdio.h#includeconio.h#includealloc.h.pdf
Solution#includestdio.h#includeconio.h#includealloc.h.pdf
 
In C++ I need help with this method that Im trying to write fillLi.pdf
In C++ I need help with this method that Im trying to write fillLi.pdfIn C++ I need help with this method that Im trying to write fillLi.pdf
In C++ I need help with this method that Im trying to write fillLi.pdf
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdf
 
Doublylinklist
DoublylinklistDoublylinklist
Doublylinklist
 
Code#include stdio.h #includemalloc.h struct node {  .pdf
Code#include stdio.h #includemalloc.h struct node {  .pdfCode#include stdio.h #includemalloc.h struct node {  .pdf
Code#include stdio.h #includemalloc.h struct node {  .pdf
 
data structure3.pptx
data structure3.pptxdata structure3.pptx
data structure3.pptx
 
Lab-2.4 101.pdf
Lab-2.4 101.pdfLab-2.4 101.pdf
Lab-2.4 101.pdf
 

Dernier

SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 

Dernier (20)

SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 

Implement Doubly Linked List

  • 1. 4. Example Programs Compile these C++programsand figure outwhatthe outputis andwhyis it appearedlike that. 4.1 Example Program 1: Add/Insertnode infront / at the beginningof a linkedlist #include <cstdlib> #include <iostream> using namespace std; struct Node { int data; Node* next; }; Node* head; void Insert(int x) { Node* temp = new Node(); temp->data = x; temp->next = head; head = temp; } void Print() { Node* temp = head; cout<<"List is : "; while(temp!=NULL) { cout<<temp->data<<"t"; temp=temp->next; } cout<<endl; } int main() { head=NULL; cout<<"How many no?n"; int n,i,x; cin>>n; for(i=0;i<n;i++) { cout<<"Enter no: n"; cin>>x; Insert(x); Print(); }
  • 3. 4.2 Example Program 2 : Add/Insert node at nth positionin the linkedlist. #include <cstdlib> #include <iostream> using namespace std; // A linked list Node struct Node { int data; struct Node* next; }; // Size of linked list int size = 0; // function to create and return a Node Node* getNode(int data) { // allocating space Node* newNode = new Node(); // inserting the required data newNode->data = data; newNode->next = NULL; return newNode; } // function to insert a Node at required position void insertPos(Node** current, int pos, int data) { // This condition to check whether the // position given is valid or not. if (pos < 1 || pos > size + 1) cout << "Invalid position!" << endl; else { // Keep looping until the pos is zero while (pos--) { if (pos == 0) { // adding Node at required position Node* temp = getNode(data); // Making the new Node to point to // the old Node at the same position temp->next = *current; // Changing the pointer of the Node previous // to the old Node to point to the new Node *current = temp; } else // Assign double pointer variable to point to the // pointer pointing to the address of next Node
  • 4. current = &(*current)->next; } size++; } } // This function prints contents // of the linked list void printList(struct Node* head) { while (head != NULL) { cout << " " << head->data; head = head->next; } cout << endl; } // Driver Code int main() { // Creating the list 3->5->8->10 Node* head = NULL; head = getNode(3); head->next = getNode(5); head->next->next = getNode(8); head->next->next->next = getNode(10); size = 4; cout << "Linked list before insertion: "; printList(head); int data = 12, pos = 3; insertPos(&head, pos, data); cout << "Linked list after first insertion is: "; printList(head); // front of the linked list data = 1, pos = 1; insertPos(&head, pos, data); cout << "Linked list after second insertion is: "; printList(head); // insertion at end of the linked list data = 15, pos = 7; insertPos(&head, pos, data); cout << "Linked list after third insertion is: "; printList(head); return 0; }
  • 5. Output: Comment: ThisProgram insertsanumberintoa premade listat a specificposition(1st ,3rd ,7th ) usingspecificvalues to representthem(dataandpos)
  • 6. 4.3 Example Program 3 : Delete node at nth positioninthe linked list #include <cstdlib> #include <iostream> using namespace std; struct Node { int data; Node* next; }; Node* head; void Insert(int x) { Node* temp = new Node(); temp->data = x; temp->next = head; head = temp; } //temp1 points to (n-1)th node void Delete (int n) { Node* temp1=head; if(n==1) { head=temp1->next; free(temp1); return; } int i; for(i=0;i<n-2;i++) { temp1=temp1->next; } Node* temp2=temp1->next; temp1->next=temp2->next; free(temp2); } void Print() { Node* temp = head; cout<<"Linked List is : "; while(temp!=NULL) { cout<<temp->data<<"t"; temp=temp->next;
  • 8. 4.4 Example Program 4 : Reverse a linkedlist. #include <cstdlib> #include <iostream> using namespace std; struct Node { int data; Node* next; }; Node* Insert(Node* head,int x) { Node* temp = new Node(); temp->data = x; temp->next = head; head = temp; return head; } Node* Reverse (Node* head) { Node *c,*p,*n; c=head; p=NULL; while(c!=NULL) { n=c->next; c->next=p; p=c; c=n; } head=p; return head; } void Print(Node* head) { cout<<"Linked List is : "; while(head!=NULL) { cout<<head->data<<"t"; head=head->next; } cout<<endl; } int main() {
  • 9. Node* head=NULL; head=Insert(head,2); head=Insert(head,3); head=Insert(head,4); head=Insert(head,5); Print(head); head=Reverse(head); Print(head); } Output: Comment: Thisprogram reversesthe orderof a predeterminedlinkedlistthrough head=Reverse(head) command thisrearrangesthe “head”or order of numberpositionsstartingfromlasttofirst
  • 10. 4.5 Example Program 5 : Print a linkedListForward and Backward using recursion. #include <cstdlib> #include <iostream> using namespace std; struct Node { int data; Node* next; }; Node* Insert(Node* head,int data) { Node* temp = new Node(); temp->data = data; temp->next = NULL; if (head==NULL)head=temp; else { Node* temp1=head; while (temp1->next != NULL) temp1=temp1->next; temp1->next=temp; } return head; } void Print(Node* p) { if(p==NULL) return; //exit condition cout<<p->data<<" "; //print data in node Print(p->next); //recursive function } void ReversePrint (Node* p) { if(p==NULL) return; ReversePrint(p->next); cout<<p->data<<" "; } int main() { Node* head=NULL; head=Insert(head,2); head=Insert(head,3); head=Insert(head,4); head=Insert(head,5); cout<<"nPrint forward : "; Print(head);
  • 11. cout<<"nnPrint Reverse/Backward : "; ReversePrint(head); cout<<endl<<endl; } Output: Comment: Thisprogram issimilartoExample program4.4 whereasthe linkedlistisprinted,reversed,andprinted againto displaythe listinitsinitial andreversedform
  • 12. 4.6 Example Program 6 : Implementationdoublylinkedlist– to print forward and backward #include <cstdlib> #include <iostream> using namespace std; struct Node { int data; Node* next; Node* prev; }; Node* head; Node* GetNewNode(int x) { Node* newNode = new Node(); newNode->data=x; newNode->next=NULL; newNode->prev=NULL; return newNode; } void InsertAtHead(int x) { Node* newNode = GetNewNode(x); if(head==NULL) { head=newNode; return; } head->prev=newNode; newNode->next=head; head=newNode; } void Print() { Node* temp = head; cout<<"Forward: "; while(temp!=NULL) { cout<<temp->data<<"t"; temp=temp->next; } cout<<endl; } void ReversePrint() {
  • 13. Node* temp = head; if(temp==NULL)return; while(temp->next!=NULL) { temp=temp->next; } cout<<"Reverse: "; while(temp!=NULL) { cout<<temp->data<<"t"; temp=temp->prev; } cout<<endl; } int main() { head=NULL; InsertAtHead(22); InsertAtHead(71); Print(); ReversePrint(); InsertAtHead(38); InsertAtHead(53); InsertAtHead(75); Print(); ReversePrint(); } Output: Comment: Thisprogram isa combinationof Example program4.4and 4.5 but utilizestwolinkedlistsbyadding another3 nodesafterthe initial forwardandreverse display