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

PDF
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
PDF
--INSTRUCTION- --It helps to first create if-then-else structure to fi.pdf
PDF
Lec-4_Linked-List (1).pdf
PDF
Data Structures in C++I am really new to C++, so links are really .pdf
PDF
Need Help!! C++ #include-iostream- #include-linkedlist-h- using namesp.pdf
PDF
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
PDF
Consider a double-linked linked list implementation with the followin.pdf
PDF
could you implement this function please, im having issues with it..pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
--INSTRUCTION- --It helps to first create if-then-else structure to fi.pdf
Lec-4_Linked-List (1).pdf
Data Structures in C++I am really new to C++, so links are really .pdf
Need Help!! C++ #include-iostream- #include-linkedlist-h- using namesp.pdf
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
Consider a double-linked linked list implementation with the followin.pdf
could you implement this function please, im having issues with it..pdf

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

PDF
How to do insertion sort on a singly linked list with no header usin.pdf
PDF
Please correct my errors upvote Clears our entire .pdf
PDF
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
PDF
Program to insert in a sorted list #includestdio.h#include.pdf
PDF
This assignment and the next (#5) involve design and development of a.pdf
PDF
C++Write a method Node Nodereverse() which reverses a list..pdf
PDF
I have been tasked to write a code for a Singly Linked list that inc.pdf
DOC
C program to insert a node in doubly linked list
PDF
#include sstream #include linkylist.h #include iostream.pdf
DOCX
C++ Please write the whole code that is needed for this assignment- wr.docx
PDF
Describe an algorithm for concatenating two singly linked lists L and.pdf
DOCX
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
PDF
In C++ I need help with this method that Im trying to write fillLi.pdf
PDF
In the class we extensively discussed a node class called IntNode in.pdf
PPTX
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
PDF
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
PPT
Mi 103 linked list
PDF
hi i have to write a java program involving link lists. i have a pro.pdf
PDF
C code on linked list #include stdio.h #include stdlib.h.pdf
PDF
Please refer this solution. This is working file for IntegersHeade.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
Problem- Describe an algorithm for concatenating two singly linked lis.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
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
C program to insert a node in doubly linked list
#include sstream #include linkylist.h #include iostream.pdf
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
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
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
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
Mi 103 linked list
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
Please refer this solution. This is working file for IntegersHeade.pdf
Ad

More from hadpadrrajeshh (20)

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

Recently uploaded (20)

PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Presentation on HIE in infants and its manifestations
PPTX
Pharma ospi slides which help in ospi learning
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
01-Introduction-to-Information-Management.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
RMMM.pdf make it easy to upload and study
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Presentation on HIE in infants and its manifestations
Pharma ospi slides which help in ospi learning
O5-L3 Freight Transport Ops (International) V1.pdf
human mycosis Human fungal infections are called human mycosis..pptx
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
01-Introduction-to-Information-Management.pdf
Microbial disease of the cardiovascular and lymphatic systems
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Final Presentation General Medicine 03-08-2024.pptx
RMMM.pdf make it easy to upload and study
O7-L3 Supply Chain Operations - ICLT Program
FourierSeries-QuestionsWithAnswers(Part-A).pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx

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; }