SlideShare a Scribd company logo
Create a link list. Add some nodes to it, search and delete nodes from it.
Solution
#include
#include
using std::cout;
using std::endl;
/*
A linked list is a list constructed using pointers. It is not fixed in
size and could grow and shrink while the program is running.
A typical defination of list nodes contains at least two parts, both the
content or date of each element and the pointer to the next element,
which is shown in the figure below.
+---------+
| Data | -----> holds the data of this element in the list.
+---------+
| pointer | -----> is a pointer to the next element in the list.
+---------+
***Attention***:
The pointer holds the address of the next element, not the address of the
data in the next element, even though they are the same in value sometimes.
And It should be set to NULL while acting as the last node of the list.
Implementation of the single linked list:
+---------+ --->+---------+ --->+---------+
| Data | | | Data | | | Data |
+---------+ | +---------+ | +---------+
| pointer |----- | pointer |----- | pointer |
+---------+ +---------+ +---------+
*/
/* definition of the list node class */
class Node
{
friend class LinkedList;
private:
int _value; /* data, can be any data type, but use integer for easiness */
Node *_pNext; /* pointer to the next node */
public:
/* Constructors with No Arguments */
Node(void)
: _pNext(NULL)
{ }
/* Constructors with a given value */
Node(int val)
: _value(val), _pNext(NULL)
{ }
/* Constructors with a given value and a link of the next node */
Node(int val, Node* next)
: _value(val), _pNext(next)
{}
/* Getters */
int getValue(void)
{ return _value; }
Node* getNext(void)
{ return _pNext; }
};
/* definition of the linked list class */
class LinkedList
{
private:
/* pointer of head node */
Node *_pHead;
/* pointer of tail node */
Node *_pTail;
public:
/* Constructors with No Arguments */
LinkedList(void);
/* Constructors with a given value of a list node */
LinkedList(int val);
/* Destructor */
~LinkedList(void);
/* Function to add a node at the head of a linked list */
void headInsert(int val);
/* Function to add a node in the middle of a linked list */
void insertAfter(Node* afterMe, int val);
/* Function to append a node to the end of a linked list */
void tailAppend(int val);
/* Function to get the node in the specific position */
Node* getNode(int pos);
/* Traversing the list and printing the value of each node */
void traverse_and_print();
};
LinkedList::LinkedList()
{
/* Initialize the head and tail node */
_pHead = _pTail = NULL;
}
LinkedList::LinkedList(int val)
{
/* Create a new node, acting as both the head and tail node */
_pHead = new Node(val);
_pTail = _pHead;
}
LinkedList::~LinkedList()
{
/*
* Leave it empty temporarily.
* It will be described in detail in the example "How to delete a linkedlist".
*/
}
void LinkedList::headInsert(int val)
{
/* The list is empty? */
if (_pHead == NULL) {
/* the same to create a new list with a given value */
_pTail = _pHead = new Node(val);
}
else
{
/* Create a new node and insert it before the head node */
Node *node = new Node(val);
node->_pNext = _pHead;
/* Update the head node */
_pHead = node;
}
}
void LinkedList::insertAfter(Node* afterMe, int val)
{
if(afterMe != NULL)
{
/* The image of inserting a node like the figures below
before inserting:
+---------+ --->---------+ --->+---------+
| afterMe | | | Node(a) | | | others |
+---------+ | +---------+ | +---------+
| next |----- | next |----- | NULL |
+---------+ +---------+ +---------+
after inserting:
(1)
+---------+ --->+---------+ --->+---------+ --->+---------+
| afterMe | (3)| | New Node| (2)| | Node(a) | | | others |
+---------+ | +---------+ | +---------+ | +---------+
| next |----- | next |----- | next |----- | NULL |
+---------+ +---------+ +---------+ +---------+
* There are three steps to insert a node into a list
* Step(1): shown as (1) in the figure above
Create a new node to be inserted
* Step(2):
Make the "next" pointer of the New Node point to the Node(a)
* Step(3):
Make the "next" pointer of the afterMe node point to the New Node
*/
afterMe->_pNext = new Node(val, afterMe->_pNext);
}
}
void LinkedList::tailAppend(int val)
{
/* The list is empty? */
if (_pHead == NULL) {
/* the same to create a new list with a given value */
_pTail = _pHead = new Node(val);
}
else
{
/* Append the new node to the tail */
_pTail->_pNext = new Node(val);
/* Update the tail pointer */
_pTail = _pTail->_pNext;
}
}
Node* LinkedList::getNode(int pos)
{
Node* p = _pHead;
/* Counter */
while (pos--) {
if (p != NULL)
p = p->_pNext;
else
return NULL;
}
return p;
}
void LinkedList::traverse_and_print()
{
Node *p = _pHead;
/* The list is empty? */
if (_pHead == NULL) {
cout << "The list is empty" << endl;
return;
}
cout << "LinkedList: ";
/* A basic way of traversing a linked list */
while (p != NULL) { /* while there are some more nodes left */
/* output the value */
cout << p->_value << " ";
/* The pointer moves along to the next one */
p = p->_pNext;
}
cout << endl;
}
int main(int argc, const char * argv[])
{
/* Create a list with only one node */
LinkedList list(1);
cout << "Create a list with only one node" << endl;
/* output the result */
list.traverse_and_print();
/* Add a node with value 2 at the head of the list */
list.headInsert(2);
cout << "Add a node with value 2 at the head of the list" << endl;
/* output the result */
list.traverse_and_print();
/* Append a node with value 3 to the end of the list */
list.tailAppend(3);
cout << "Append a node with value 3 to the end of the list" << endl;
/* output the result */
list.traverse_and_print();
/* Insert a node with value 4 after the first node of the list */
list.insertAfter(list.getNode(0), 4);
cout << "Insert a node with value 4 after the first node of the list" << endl;
/* output the result */
list.traverse_and_print();
return 0;
}

More Related Content

Similar to Create a link list. Add some nodes to it, search and delete nodes fro.pdf

How to do insertion sort on a singly linked list with no header usin.pdf
How to do insertion sort on a singly linked list with no header usin.pdfHow to do insertion sort on a singly linked list with no header usin.pdf
How to do insertion sort on a singly linked list with no header usin.pdf
arihantelehyb
 
Please correct my errors upvote Clears our entire .pdf
Please correct my errors upvote      Clears our entire .pdfPlease correct my errors upvote      Clears our entire .pdf
Please correct my errors upvote Clears our entire .pdf
kitty811
 
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
Problem- Describe an algorithm for concatenating two singly linked lis.pdfProblem- Describe an algorithm for concatenating two singly linked lis.pdf
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
kingsandqueens3
 
Program to insert in a sorted list #includestdio.h#include.pdf
 Program to insert in a sorted list #includestdio.h#include.pdf Program to insert in a sorted list #includestdio.h#include.pdf
Program to insert in a sorted list #includestdio.h#include.pdf
sudhirchourasia86
 
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
EricvtJFraserr
 
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
arjunenterprises1978
 
I have been tasked to write a code for a Singly Linked list that inc.pdf
I have been tasked to write a code for a Singly Linked list that inc.pdfI have been tasked to write a code for a Singly Linked list that inc.pdf
I have been tasked to write a code for a Singly Linked list that inc.pdf
arkmuzikllc
 
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
Sourav Gayen
 
#include sstream #include linkylist.h #include iostream.pdf
#include sstream #include linkylist.h #include iostream.pdf#include sstream #include linkylist.h #include iostream.pdf
#include sstream #include linkylist.h #include iostream.pdf
aravlitraders2012
 
C++ Please write the whole code that is needed for this assignment- wr.docx
C++ Please write the whole code that is needed for this assignment- wr.docxC++ Please write the whole code that is needed for this assignment- wr.docx
C++ Please write the whole code that is needed for this assignment- wr.docx
BrianGHiNewmanv
 
Describe an algorithm for concatenating two singly linked lists L and.pdf
Describe an algorithm for concatenating two singly linked lists L and.pdfDescribe an algorithm for concatenating two singly linked lists L and.pdf
Describe an algorithm for concatenating two singly linked lists L and.pdf
deepak596396
 
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjhlinked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
vasavim9
 
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
fantoosh1
 
In the class we extensively discussed a node class called IntNode in.pdf
In the class we extensively discussed a node class called IntNode in.pdfIn the class we extensively discussed a node class called IntNode in.pdf
In the class we extensively discussed a node class called IntNode in.pdf
arjunstores123
 
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptxData Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
RashidFaridChishti
 
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdfTHE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
fathimahardwareelect
 
Mi 103 linked list
Mi 103 linked listMi 103 linked list
Mi 103 linked list
Amit Vats
 
hi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfhi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdf
archgeetsenterprises
 
C code on linked list #include stdio.h #include stdlib.h.pdf
 C code on linked list #include stdio.h #include stdlib.h.pdf C code on linked list #include stdio.h #include stdlib.h.pdf
C code on linked list #include stdio.h #include stdlib.h.pdf
deepua8
 
Please refer this solution. This is working file for IntegersHeade.pdf
Please refer this solution. This is working file for IntegersHeade.pdfPlease refer this solution. This is working file for IntegersHeade.pdf
Please refer this solution. This is working file for IntegersHeade.pdf
sooryasalini
 

Similar to Create a link list. Add some nodes to it, search and delete nodes fro.pdf (20)

How to do insertion sort on a singly linked list with no header usin.pdf
How to do insertion sort on a singly linked list with no header usin.pdfHow to do insertion sort on a singly linked list with no header usin.pdf
How to do insertion sort on a singly linked list with no header usin.pdf
 
Please correct my errors upvote Clears our entire .pdf
Please correct my errors upvote      Clears our entire .pdfPlease correct my errors upvote      Clears our entire .pdf
Please correct my errors upvote Clears our entire .pdf
 
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
Problem- Describe an algorithm for concatenating two singly linked lis.pdfProblem- Describe an algorithm for concatenating two singly linked lis.pdf
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
 
Program to insert in a sorted list #includestdio.h#include.pdf
 Program to insert in a sorted list #includestdio.h#include.pdf Program to insert in a sorted list #includestdio.h#include.pdf
Program to insert in a sorted list #includestdio.h#include.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
 
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
 
I have been tasked to write a code for a Singly Linked list that inc.pdf
I have been tasked to write a code for a Singly Linked list that inc.pdfI have been tasked to write a code for a Singly Linked list that inc.pdf
I have been tasked to write a code for a Singly Linked list that inc.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 sstream #include linkylist.h #include iostream.pdf
#include sstream #include linkylist.h #include iostream.pdf#include sstream #include linkylist.h #include iostream.pdf
#include sstream #include linkylist.h #include iostream.pdf
 
C++ Please write the whole code that is needed for this assignment- wr.docx
C++ Please write the whole code that is needed for this assignment- wr.docxC++ Please write the whole code that is needed for this assignment- wr.docx
C++ Please write the whole code that is needed for this assignment- wr.docx
 
Describe an algorithm for concatenating two singly linked lists L and.pdf
Describe an algorithm for concatenating two singly linked lists L and.pdfDescribe an algorithm for concatenating two singly linked lists L and.pdf
Describe an algorithm for concatenating two singly linked lists L and.pdf
 
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjhlinked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
 
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
 
In the class we extensively discussed a node class called IntNode in.pdf
In the class we extensively discussed a node class called IntNode in.pdfIn the class we extensively discussed a node class called IntNode in.pdf
In the class we extensively discussed a node class called IntNode in.pdf
 
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptxData Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
 
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdfTHE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
 
Mi 103 linked list
Mi 103 linked listMi 103 linked list
Mi 103 linked list
 
hi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfhi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdf
 
C code on linked list #include stdio.h #include stdlib.h.pdf
 C code on linked list #include stdio.h #include stdlib.h.pdf C code on linked list #include stdio.h #include stdlib.h.pdf
C code on linked list #include stdio.h #include stdlib.h.pdf
 
Please refer this solution. This is working file for IntegersHeade.pdf
Please refer this solution. This is working file for IntegersHeade.pdfPlease refer this solution. This is working file for IntegersHeade.pdf
Please refer this solution. This is working file for IntegersHeade.pdf
 

More from hadpadrrajeshh

Given a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdfGiven a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdf
hadpadrrajeshh
 
Gather information on the following two disasters Space shuttle Ch.pdf
Gather information on the following two disasters Space shuttle Ch.pdfGather information on the following two disasters Space shuttle Ch.pdf
Gather information on the following two disasters Space shuttle Ch.pdf
hadpadrrajeshh
 
Determine the Laplace transform, F(s), of the following time signal..pdf
Determine the Laplace transform, F(s), of the following time signal..pdfDetermine the Laplace transform, F(s), of the following time signal..pdf
Determine the Laplace transform, F(s), of the following time signal..pdf
hadpadrrajeshh
 
Describe the difference between a monitor and a semaphoreSolutio.pdf
Describe the difference between a monitor and a semaphoreSolutio.pdfDescribe the difference between a monitor and a semaphoreSolutio.pdf
Describe the difference between a monitor and a semaphoreSolutio.pdf
hadpadrrajeshh
 
A speedometer is a measuring instrument. What are the independent and.pdf
A speedometer is a measuring instrument. What are the independent and.pdfA speedometer is a measuring instrument. What are the independent and.pdf
A speedometer is a measuring instrument. What are the independent and.pdf
hadpadrrajeshh
 
A recent study by the EPA has determined that the amount of contamin.pdf
A recent study by the EPA has determined that the amount of contamin.pdfA recent study by the EPA has determined that the amount of contamin.pdf
A recent study by the EPA has determined that the amount of contamin.pdf
hadpadrrajeshh
 
choice one correct answerRocks containing iron, calcium, magnesium.pdf
choice one correct answerRocks containing iron, calcium, magnesium.pdfchoice one correct answerRocks containing iron, calcium, magnesium.pdf
choice one correct answerRocks containing iron, calcium, magnesium.pdf
hadpadrrajeshh
 
1.write down the RTL for the SUBT instructions. 2.Draw a flowchart.pdf
1.write down the RTL for the SUBT instructions. 2.Draw a flowchart.pdf1.write down the RTL for the SUBT instructions. 2.Draw a flowchart.pdf
1.write down the RTL for the SUBT instructions. 2.Draw a flowchart.pdf
hadpadrrajeshh
 
Write a Java application that asks for an integer and returns its fac.pdf
Write a Java application that asks for an integer and returns its fac.pdfWrite a Java application that asks for an integer and returns its fac.pdf
Write a Java application that asks for an integer and returns its fac.pdf
hadpadrrajeshh
 
Where should seaweeds and kelps be classified Give characteristics .pdf
Where should seaweeds and kelps be classified Give characteristics .pdfWhere should seaweeds and kelps be classified Give characteristics .pdf
Where should seaweeds and kelps be classified Give characteristics .pdf
hadpadrrajeshh
 
What is the name of the connective tissue that divides the se.pdf
What is the name of the connective tissue that divides the se.pdfWhat is the name of the connective tissue that divides the se.pdf
What is the name of the connective tissue that divides the se.pdf
hadpadrrajeshh
 
What is the current ratio of Chester Use the results of the Balance.pdf
What is the current ratio of Chester Use the results of the Balance.pdfWhat is the current ratio of Chester Use the results of the Balance.pdf
What is the current ratio of Chester Use the results of the Balance.pdf
hadpadrrajeshh
 
What is glass-transition temperature Give a material example. How ma.pdf
What is glass-transition temperature Give a material example. How ma.pdfWhat is glass-transition temperature Give a material example. How ma.pdf
What is glass-transition temperature Give a material example. How ma.pdf
hadpadrrajeshh
 
What are some contributions to the development of industrializat.pdf
What are some contributions to the development of industrializat.pdfWhat are some contributions to the development of industrializat.pdf
What are some contributions to the development of industrializat.pdf
hadpadrrajeshh
 
The “creative revolution” that handed more authority to agency art d.pdf
The “creative revolution” that handed more authority to agency art d.pdfThe “creative revolution” that handed more authority to agency art d.pdf
The “creative revolution” that handed more authority to agency art d.pdf
hadpadrrajeshh
 
The three main coefficients (not properties or dimensionless numbers).pdf
The three main coefficients (not properties or dimensionless numbers).pdfThe three main coefficients (not properties or dimensionless numbers).pdf
The three main coefficients (not properties or dimensionless numbers).pdf
hadpadrrajeshh
 
The project will study the coordination of multiple threads using se.pdf
The project will study the coordination of multiple threads using se.pdfThe project will study the coordination of multiple threads using se.pdf
The project will study the coordination of multiple threads using se.pdf
hadpadrrajeshh
 
The positive selection process for T lymphocytes that occurs In the t.pdf
The positive selection process for T lymphocytes that occurs In the t.pdfThe positive selection process for T lymphocytes that occurs In the t.pdf
The positive selection process for T lymphocytes that occurs In the t.pdf
hadpadrrajeshh
 
The local public health agency has received reports of an outbreak o.pdf
The local public health agency has received reports of an outbreak o.pdfThe local public health agency has received reports of an outbreak o.pdf
The local public health agency has received reports of an outbreak o.pdf
hadpadrrajeshh
 
how are musical sounds produced Explain your reasoning.Solution.pdf
how are musical sounds produced Explain your reasoning.Solution.pdfhow are musical sounds produced Explain your reasoning.Solution.pdf
how are musical sounds produced Explain your reasoning.Solution.pdf
hadpadrrajeshh
 

More from hadpadrrajeshh (20)

Given a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdfGiven a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdf
 
Gather information on the following two disasters Space shuttle Ch.pdf
Gather information on the following two disasters Space shuttle Ch.pdfGather information on the following two disasters Space shuttle Ch.pdf
Gather information on the following two disasters Space shuttle Ch.pdf
 
Determine the Laplace transform, F(s), of the following time signal..pdf
Determine the Laplace transform, F(s), of the following time signal..pdfDetermine the Laplace transform, F(s), of the following time signal..pdf
Determine the Laplace transform, F(s), of the following time signal..pdf
 
Describe the difference between a monitor and a semaphoreSolutio.pdf
Describe the difference between a monitor and a semaphoreSolutio.pdfDescribe the difference between a monitor and a semaphoreSolutio.pdf
Describe the difference between a monitor and a semaphoreSolutio.pdf
 
A speedometer is a measuring instrument. What are the independent and.pdf
A speedometer is a measuring instrument. What are the independent and.pdfA speedometer is a measuring instrument. What are the independent and.pdf
A speedometer is a measuring instrument. What are the independent and.pdf
 
A recent study by the EPA has determined that the amount of contamin.pdf
A recent study by the EPA has determined that the amount of contamin.pdfA recent study by the EPA has determined that the amount of contamin.pdf
A recent study by the EPA has determined that the amount of contamin.pdf
 
choice one correct answerRocks containing iron, calcium, magnesium.pdf
choice one correct answerRocks containing iron, calcium, magnesium.pdfchoice one correct answerRocks containing iron, calcium, magnesium.pdf
choice one correct answerRocks containing iron, calcium, magnesium.pdf
 
1.write down the RTL for the SUBT instructions. 2.Draw a flowchart.pdf
1.write down the RTL for the SUBT instructions. 2.Draw a flowchart.pdf1.write down the RTL for the SUBT instructions. 2.Draw a flowchart.pdf
1.write down the RTL for the SUBT instructions. 2.Draw a flowchart.pdf
 
Write a Java application that asks for an integer and returns its fac.pdf
Write a Java application that asks for an integer and returns its fac.pdfWrite a Java application that asks for an integer and returns its fac.pdf
Write a Java application that asks for an integer and returns its fac.pdf
 
Where should seaweeds and kelps be classified Give characteristics .pdf
Where should seaweeds and kelps be classified Give characteristics .pdfWhere should seaweeds and kelps be classified Give characteristics .pdf
Where should seaweeds and kelps be classified Give characteristics .pdf
 
What is the name of the connective tissue that divides the se.pdf
What is the name of the connective tissue that divides the se.pdfWhat is the name of the connective tissue that divides the se.pdf
What is the name of the connective tissue that divides the se.pdf
 
What is the current ratio of Chester Use the results of the Balance.pdf
What is the current ratio of Chester Use the results of the Balance.pdfWhat is the current ratio of Chester Use the results of the Balance.pdf
What is the current ratio of Chester Use the results of the Balance.pdf
 
What is glass-transition temperature Give a material example. How ma.pdf
What is glass-transition temperature Give a material example. How ma.pdfWhat is glass-transition temperature Give a material example. How ma.pdf
What is glass-transition temperature Give a material example. How ma.pdf
 
What are some contributions to the development of industrializat.pdf
What are some contributions to the development of industrializat.pdfWhat are some contributions to the development of industrializat.pdf
What are some contributions to the development of industrializat.pdf
 
The “creative revolution” that handed more authority to agency art d.pdf
The “creative revolution” that handed more authority to agency art d.pdfThe “creative revolution” that handed more authority to agency art d.pdf
The “creative revolution” that handed more authority to agency art d.pdf
 
The three main coefficients (not properties or dimensionless numbers).pdf
The three main coefficients (not properties or dimensionless numbers).pdfThe three main coefficients (not properties or dimensionless numbers).pdf
The three main coefficients (not properties or dimensionless numbers).pdf
 
The project will study the coordination of multiple threads using se.pdf
The project will study the coordination of multiple threads using se.pdfThe project will study the coordination of multiple threads using se.pdf
The project will study the coordination of multiple threads using se.pdf
 
The positive selection process for T lymphocytes that occurs In the t.pdf
The positive selection process for T lymphocytes that occurs In the t.pdfThe positive selection process for T lymphocytes that occurs In the t.pdf
The positive selection process for T lymphocytes that occurs In the t.pdf
 
The local public health agency has received reports of an outbreak o.pdf
The local public health agency has received reports of an outbreak o.pdfThe local public health agency has received reports of an outbreak o.pdf
The local public health agency has received reports of an outbreak o.pdf
 
how are musical sounds produced Explain your reasoning.Solution.pdf
how are musical sounds produced Explain your reasoning.Solution.pdfhow are musical sounds produced Explain your reasoning.Solution.pdf
how are musical sounds produced Explain your reasoning.Solution.pdf
 

Recently uploaded

The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
Celine George
 

Recently uploaded (20)

The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
 

Create a link list. Add some nodes to it, search and delete nodes fro.pdf

  • 1. Create a link list. Add some nodes to it, search and delete nodes from it. Solution #include #include using std::cout; using std::endl; /* A linked list is a list constructed using pointers. It is not fixed in size and could grow and shrink while the program is running. A typical defination of list nodes contains at least two parts, both the content or date of each element and the pointer to the next element, which is shown in the figure below. +---------+ | Data | -----> holds the data of this element in the list. +---------+ | pointer | -----> is a pointer to the next element in the list. +---------+ ***Attention***: The pointer holds the address of the next element, not the address of the data in the next element, even though they are the same in value sometimes. And It should be set to NULL while acting as the last node of the list. Implementation of the single linked list: +---------+ --->+---------+ --->+---------+ | Data | | | Data | | | Data | +---------+ | +---------+ | +---------+ | pointer |----- | pointer |----- | pointer | +---------+ +---------+ +---------+ */
  • 2. /* definition of the list node class */ class Node { friend class LinkedList; private: int _value; /* data, can be any data type, but use integer for easiness */ Node *_pNext; /* pointer to the next node */ public: /* Constructors with No Arguments */ Node(void) : _pNext(NULL) { } /* Constructors with a given value */ Node(int val) : _value(val), _pNext(NULL) { } /* Constructors with a given value and a link of the next node */ Node(int val, Node* next) : _value(val), _pNext(next) {} /* Getters */ int getValue(void) { return _value; } Node* getNext(void) { return _pNext; } }; /* definition of the linked list class */ class LinkedList { private:
  • 3. /* pointer of head node */ Node *_pHead; /* pointer of tail node */ Node *_pTail; public: /* Constructors with No Arguments */ LinkedList(void); /* Constructors with a given value of a list node */ LinkedList(int val); /* Destructor */ ~LinkedList(void); /* Function to add a node at the head of a linked list */ void headInsert(int val); /* Function to add a node in the middle of a linked list */ void insertAfter(Node* afterMe, int val); /* Function to append a node to the end of a linked list */ void tailAppend(int val); /* Function to get the node in the specific position */ Node* getNode(int pos); /* Traversing the list and printing the value of each node */ void traverse_and_print(); }; LinkedList::LinkedList() { /* Initialize the head and tail node */ _pHead = _pTail = NULL; } LinkedList::LinkedList(int val) { /* Create a new node, acting as both the head and tail node */ _pHead = new Node(val); _pTail = _pHead;
  • 4. } LinkedList::~LinkedList() { /* * Leave it empty temporarily. * It will be described in detail in the example "How to delete a linkedlist". */ } void LinkedList::headInsert(int val) { /* The list is empty? */ if (_pHead == NULL) { /* the same to create a new list with a given value */ _pTail = _pHead = new Node(val); } else { /* Create a new node and insert it before the head node */ Node *node = new Node(val); node->_pNext = _pHead; /* Update the head node */ _pHead = node; } } void LinkedList::insertAfter(Node* afterMe, int val) { if(afterMe != NULL) { /* The image of inserting a node like the figures below before inserting: +---------+ --->---------+ --->+---------+ | afterMe | | | Node(a) | | | others | +---------+ | +---------+ | +---------+ | next |----- | next |----- | NULL | +---------+ +---------+ +---------+ after inserting:
  • 5. (1) +---------+ --->+---------+ --->+---------+ --->+---------+ | afterMe | (3)| | New Node| (2)| | Node(a) | | | others | +---------+ | +---------+ | +---------+ | +---------+ | next |----- | next |----- | next |----- | NULL | +---------+ +---------+ +---------+ +---------+ * There are three steps to insert a node into a list * Step(1): shown as (1) in the figure above Create a new node to be inserted * Step(2): Make the "next" pointer of the New Node point to the Node(a) * Step(3): Make the "next" pointer of the afterMe node point to the New Node */ afterMe->_pNext = new Node(val, afterMe->_pNext); } } void LinkedList::tailAppend(int val) { /* The list is empty? */ if (_pHead == NULL) { /* the same to create a new list with a given value */ _pTail = _pHead = new Node(val); } else { /* Append the new node to the tail */ _pTail->_pNext = new Node(val); /* Update the tail pointer */ _pTail = _pTail->_pNext; } } Node* LinkedList::getNode(int pos) { Node* p = _pHead;
  • 6. /* Counter */ while (pos--) { if (p != NULL) p = p->_pNext; else return NULL; } return p; } void LinkedList::traverse_and_print() { Node *p = _pHead; /* The list is empty? */ if (_pHead == NULL) { cout << "The list is empty" << endl; return; } cout << "LinkedList: "; /* A basic way of traversing a linked list */ while (p != NULL) { /* while there are some more nodes left */ /* output the value */ cout << p->_value << " "; /* The pointer moves along to the next one */ p = p->_pNext; } cout << endl; } int main(int argc, const char * argv[]) { /* Create a list with only one node */ LinkedList list(1); cout << "Create a list with only one node" << endl; /* output the result */ list.traverse_and_print();
  • 7. /* Add a node with value 2 at the head of the list */ list.headInsert(2); cout << "Add a node with value 2 at the head of the list" << endl; /* output the result */ list.traverse_and_print(); /* Append a node with value 3 to the end of the list */ list.tailAppend(3); cout << "Append a node with value 3 to the end of the list" << endl; /* output the result */ list.traverse_and_print(); /* Insert a node with value 4 after the first node of the list */ list.insertAfter(list.getNode(0), 4); cout << "Insert a node with value 4 after the first node of the list" << endl; /* output the result */ list.traverse_and_print(); return 0; }