SlideShare a Scribd company logo
LINKED LISTS
DATA STRUCTURES
AND ALGORITHMS
1
WHAT IS A LIST?
 A list is a collection of items:
 It can have an arbitrary length
 Objects / elements can be inserted or removed at
arbitrary locations in the list
 A list can be traversed in order one item at a time
2
LIST AS AN ADT
 A list is a finite sequence (possibly empty) of
elements with basic operations that vary from
one application to another.
 Basic operations commonly include:
 Construction: Allocate and initialize a list object
(usually empty)
 Empty: Check if list is empty
 Insert: Add an item to the list at any point
 Delete: Remove an item from the list at any point
 Traverse: Visiting each node of list
3
VARIATIONS OF LINKED LISTS
 Singly linked lists
 Circular linked lists
 Doubly linked lists
 Circular doubly linked list
4
LINKED LIST
Minimal Requirements
 Locate the first element
 Given the location of any list element, find its successor
 Determine if at the end of the list
5
LINKED LIST TERMINOLOGIES
 Traversal of List
 Means to visit every element or node in the list
beginning from first to last.
 Predecessor and Successor
 In the list of elements, for any location n, (n-1) is
predecessor and (n+1) is successor
 In other words, for any location n in the list, the left
element is predecessor and the right element is
successor.
 Also, the first element does not have predecessor
and the last element does not have successor. 6
LINKED LISTS
 A linked list is a series of connected nodes
 Each node contains at least
 A piece of data (any type)
 Pointer to the next node in the list
 Head: pointer to the first node
 The last node points to NULL
A 
Head
B C
A
data pointer
node
7
LISTS – ANOTHER PERSPECTIVE
A list is a linear collection of varying length of
homogeneous components.
Homogeneous: All components are of the same
type.
Linear: Components are ordered in a line (hence
called Linear linked lists).
8
ARRAYS VS LISTS
• Arrays are lists that have a fixed size in memory.
• The programmer must keep track of the length of the
array
• No matter how many elements of the array are used
in a program, the array has the same amount of
allocated space.
• Array elements are stored in successive memory
locations. Also, order of elements stored in array is
same logically and physically.
9
• A linked list takes up only as much space in memory
as is needed for the length of the list.
• The list expands or contracts as you add or delete
elements.
• In linked list the elements are not stored in successive
memory location
• Elements can be added to (or deleted from) either
end, or added to (or deleted from)the middle of the
list.
ARRAYS VS LISTS
10
ARRAY VERSUS LINKED LISTS
 Linked lists are more complex to code and manage
than arrays, but they have some distinct advantages.
 Dynamic: a linked list can easily grow and shrink in size.
 We don’t need to know how many nodes will be in the list. They
are created in memory as needed.
 In contrast, the size of a C++ array is fixed at compilation time.
 Easy and fast insertions and deletions
 To insert or delete an element in an array, we need to copy to
temporary variables to make room for new elements or close the
gap caused by deleted elements.
 With a linked list, no need to move other nodes. Only need to reset
some pointers.
11
A Linked List
12
An Array
BASIC OPERATIONS OF LINKED LIST
 Linked List, a linear collection of data items, called
nodes, where order is given y means of pointers.
 Elements:
 Each node is divided into two parts:
 Information
 Link ( pointing towards the next node)
 (Common) Operations of Linked List
 IsEmpty: determine whether or not the list is empty
 InsertNode: insert a new node at a particular position
 FindNode: find a node with a given value
 DeleteNode: delete a node with a given value
 DisplayList: print all the nodes in the list
13
AN INTEGER LINKED LIST
list
10 13 5 2
First Node of List
data next NULL
Last Node of List
14
CREATING A LIST NODE
p 10
struct Node {
int data; // data in node
Node *next; // Pointer to next node
};
Node *p;
p = new Node;
p - > data = 10;
p - > next = NULL;
15
CREATING A LIST NODE
p 10
class Node {
public:
int data; // data in node
Node *next; // Pointer to next node
};
Node *p;
p = new Node;
p - > data = 10;
p - > next = NULL;
16
To avoid get/set methods
THE NULL POINTER
NULL is a special pointer value that does not reference
any memory cell.
If a pointer is not currently in use, it should be set to
NULL so that one can determine that it is not pointing
to a valid address:
int *p;
p = NULL;
17
18
Singly Linked List
AN INTEGER (SINGLY) LINKED LIST
list
10 13 5 2
First Node of List
data next NULL
Last Node of List
class Node {
public:
int data;
Node *next;
};
Basic Concepts
19
JOINING TWO NODES
Node *p, *q;
p = new Node;
p - > data = 10;
p - > next = NULL;
q = new Node;
q - > data = 6;
q - > next = NULL;
p - > next = q;
p 10
q 6
6p 10
q
Basic Concepts
20
ACCESSING LIST DATA
Expression
p
p - > data
p - > next
p - > next - > data
p - > next - > next
6p 10
Node 1 Node 2
Value
Pointer to first node (head)
10
Pointer to next node
6
NULL pointer
Basic Concepts
21
BUILDING A LIST FROM 1 TO N
class Node {
public:
int data;
Node *next;
};
Node *head = NULL; // pointer to the list head
Node *lastNodePtr = NULL; // pointer to last node
head lastNodePtr
Basic Concepts
23
CREATING THE FIRST NODE
Node *ptr; // declare a pointer to Node
ptr = new Node; // create a new Node
ptr - > data = 1;
ptr - > next = NULL;
head = ptr; // new node is first
lastNodePtr = ptr; // and last node in list
head 1
ptr
lastNodePtr
Basic Concepts
24
ADDING MORE NODES
for (int i = 2; i < = n; i ++ ) {
ptr = new Node;
ptr - > data = i;
ptr - > next = NULL;
lastNodePtr - > next = ptr; // order is
lastNodePtr = ptr; // important
}
2head 1
ptr
lastNodePtr
Basic Concepts
25
2head 1
ptr
lastNodePtr
2head 1
ptr
lastNodePtr
3
•Create a new node with data field set to 3
•Its next pointer should point to NULL
Initially
Basic Concepts
26
2head 1
ptr
lastNodePtr
2head 1
ptr
lastNodePtr
3
The next pointer of the node which was previously
last should now point to newly created node
“lastNodePtr->next=ptr”
Basic Concepts
27
2head 1
ptr
lastNodePtr
2head 1
ptr
lastNodePtr
3
The next pointer of the node which was previously
last should now point to newly created node
“lastNodePtr->next=ptr”
Basic Concepts
28
2head 1
ptr
lastNodePtr
2head 1
ptr
lastNodePtr
3
LastNodePtr should now point to the newly created
Node “lastNodePtr = ptr;”
Basic Concepts
29
3head 1
ptr
lastNodePtr
2
RE-ARRANGING THE VIEW
Basic Concepts
30
BASIC LINKED LIST OPERATIONS
 Traversing through the list
 Node Insertion
 Insertion at the beginning of the list
 Insertion at the end of the list
 Insertion in the middle of the list
 Node Deletion
 Deletion at the beginning of the list
 Deletion at the end of the list
 Deletion from the middle of the list
31
32
Traversing the list
TRAVERSING THE LIST
33
ptr = first;
while (ptr != null_value)
{
Process data part of node pointed to by ptr
ptr = next part of node pointed to by ptr;
}
34
9 17 22 26 34first
ptr
9 17 22 26 34first
ptr
..
.
9 17 22 26 34first
ptr
9 17 22 26 34first
ptr
ptr = first;
while (ptr != null_value)
{
Process data part of
node pointed to by ptr;
ptr = next part of node
pointed to by ptr;
}
TRAVERSING THE LIST
35
Node * currNode;
currNode = head;
while (currNode != NULL)
{
cout<< currNode->data;
currNode = currNode->next;
}
NODE INSERTION
 Insertion at the beginning of the list
 Insertion at the end of the list
 Insertion in the middle of the list
36
NODE INSERTION AT THE BEGINNING
Steps:
 Create a node
 Set the node data values
 Connect the pointers
48 17 142head //
Step 1 Step 2
Initial list
List after Step 3
head 93
NODE INSERTION AT THE BEGINNING
48 17 142head //Initial list
head
Node *ptr;
ptr = new Node;
ptr - > data = 93;
ptr - > next = head;
head = ptr; 93
head 93
Rearrange:
ptr
ptr
head
NODE INSERTION AT THE END
Steps:
 Create a Node
 Set the node data values
 Connect the pointers
48 17 142head //
Step 1 Step 2
List after Step 3
Initial list
NODE INSERTION AT THE END
48 17 142head //Initial list
ptr
Node * ptr;
ptr = head;
while (ptr->next != NULL)
{
ptr = ptr->next;
}
Need a pointer at the last
node
NODE INSERTION AT THE END
48 17 142head //Initial list
ptr
Node * p;
p = new Node;
p -> data = 150;
p -> next = NULL;
150 //
p
NODE INSERTION AT THE END
48 17 142head
ptr
Node * p;
p = new Node;
p -> data = 150;
p -> next = NULL;
ptr -> next = p;
150 //
p
NODE INSERTION AT ARBITRARY POSITION
Steps:
 Create a Node
 Set the node data values
 Break pointer connection
 Re-connect the pointers
Step 1 Step 2
Step 3
Step 4
NODE INSERTION AT ARBITRARY POSITION
Steps:
 Create a Node
 Set the node data values
 Break pointer connection
 Re-connect the pointers
Need a pointer on the node after which a new node is to be
Inserted. For instance, if new node is to be inserted after
the node having value ‘17’, we need a pointer at this node
ptr
How to get pointer on desired node?
NODE INSERTION AT ARBITRARY POSITION
Suppose we want to insert a node after the node having
value ‘x’:
ptr
Node * ptr;
ptr = head;
while (ptr->data != x)
{
ptr = ptr->next;
}
NODE INSERTION AT ARBITRARY POSITION
ptr
Node * ptr;
ptr = head;
while (ptr->data != x)
{
ptr = ptr->next;
}
Node * p;
p = new Node;
p -> data = 100;
p -> next = NULL;
150 //
p
NODE INSERTION AT ARBITRARY POSITION
ptr
Node * ptr;
ptr = head;
while (ptr->data != x)
{
ptr = ptr->next;
}
Node * p;
p = new Node;
p -> data = 150;
p -> next = NULL;
p -> next = ptr -> next;
ptr -> next = p;
150
p
NODE DELETION
 Deleting from the beginning of the list
 Deleting from the end of the list
 Deleting from the middle of the list
DELETING FROM THE BEGINNING
Steps:
 Break the pointer connection
 Re-connect the nodes
 Delete the node
4 17head 426
4 17
head
426
4 17head 42
DELETING FROM THE BEGINNING
4 17
head
426
head
4 17 426
4 17head 42
Node * ptr;
ptr = head;
head = head ->next;
delete ptr;
ptr
ptr
head
DELETING FROM THE END
Steps:
 Break the pointer connection
 Set previous node pointer to NULL
 Delete the node
4 17head 426
4 17head 426
4 176head
DELETING FROM THE END
4 17head 426
We need a pointer one node before the node to be deleted
predPtr
Node * ptr;
Node * predPtr;
ptr = head;
predPtr = NULL;
while (ptr->next != NULL)
{
predPtr = ptr;
ptr = ptr->next;
}
ptr
DELETING FROM THE END
4 176head
predPtr -> next = NULL;
delete ptr;
4 17head 426
predPtr ptr
4 17head 426
predPtr ptr
4 17head 426
predPtr ptr
DELETING FROM AN ARBITRARY POSITION
Steps:
 Set previous Node pointer to next node
 Break Node pointer connection
 Delete the node
4 17 42head
4 17head 42
4head 42
DELETING FROM AN ARBITRARY POSITION
4 17 42head
We need a pointer on the node to be deleted (as well a pointer to one
node before the node to be deleted)
predPtr ptr
Node * ptr;
Node * predPtr;
ptr = head;
predPtr = NULL;
while (ptr->data != x)
{
predPtr = ptr;
ptr = ptr->next;
}
Given the value of the node to be
deleted, assume this to be variable
‘x’
Keep moving a pointer until the
required node is reached
DELETING FROM AN ARBITRARY POSITION
4 17 42head
predPtr ptr
predPtr -> next = ptr -> next;
delete ptr;
4 17 42head
predPtr ptr
4 17 42head
predPtr ptr
PROS AND CONS OF LINKED LISTS
• Access any item as long as external link to first item
maintained
• Insert new item without shifting
• Delete existing item without shifting
• Can expand/contract as necessary
• Overhead of links: used only internally, pure overhead
• No longer have direct access to each element of the
list
• We must go through first element, and then second,
and then third, etc. 57

More Related Content

What's hot (20)

PPT
3.2 insertion sort
Krish_ver2
 
PPTX
Stack and Queue by M.Gomathi Lecturer
gomathi chlm
 
PPTX
Linked List
Ashim Lamichhane
 
PPT
Queue Data Structure
Lovely Professional University
 
PPTX
Queue in Data Structure
Janki Shah
 
PPTX
Array ADT(Abstract Data Type)|Data Structure
Akash Gaur
 
PPTX
Array operations
ZAFAR444
 
PPT
Data Structure and Algorithms Binary Search Tree
ManishPrajapati78
 
PPTX
Linked list
Arbind Mandal
 
PPTX
Data Structures - Lecture 7 [Linked List]
Muhammad Hammad Waseem
 
PDF
Array data structure
maamir farooq
 
PPTX
linked list in data structure
shameen khan
 
PPTX
10. Search Tree - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
PDF
Applications of stack
eShikshak
 
PPT
Heaps
Hafiz Atif Amin
 
PPT
Data Structure and Algorithms Linked List
ManishPrajapati78
 
PPTX
Linked list
Md. Afif Al Mamun
 
PPTX
Data Structures - Lecture 9 [Stack & Queue using Linked List]
Muhammad Hammad Waseem
 
PPTX
Stack & Queue using Linked List in Data Structure
Meghaj Mallick
 
3.2 insertion sort
Krish_ver2
 
Stack and Queue by M.Gomathi Lecturer
gomathi chlm
 
Linked List
Ashim Lamichhane
 
Queue Data Structure
Lovely Professional University
 
Queue in Data Structure
Janki Shah
 
Array ADT(Abstract Data Type)|Data Structure
Akash Gaur
 
Array operations
ZAFAR444
 
Data Structure and Algorithms Binary Search Tree
ManishPrajapati78
 
Linked list
Arbind Mandal
 
Data Structures - Lecture 7 [Linked List]
Muhammad Hammad Waseem
 
Array data structure
maamir farooq
 
linked list in data structure
shameen khan
 
10. Search Tree - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
Applications of stack
eShikshak
 
Data Structure and Algorithms Linked List
ManishPrajapati78
 
Linked list
Md. Afif Al Mamun
 
Data Structures - Lecture 9 [Stack & Queue using Linked List]
Muhammad Hammad Waseem
 
Stack & Queue using Linked List in Data Structure
Meghaj Mallick
 

Similar to Linked lists a (20)

PPTX
Linked List.pptx
PoonamPatil120
 
PPTX
DS_LinkedList.pptx
msohail37
 
PPT
Algo>ADT list & linked list
Ain-ul-Moiz Khawaja
 
PPT
Lecture 3 List of Data Structures & Algorithms
haseebanjum2611
 
PPT
dynamicList.ppt
ssuser0be977
 
PPTX
data structures lists operation of lists
muskans14
 
PPTX
Linked list (1).pptx
rajveersingh643731
 
PPTX
DSL Unit 4 (Linked list) (PPT)SE3rd sem sppu.pptx
vaibhavkore8
 
PDF
ds-lecture-4-171012041008 (1).pdf
KamranAli649587
 
PPT
Operations on linked list
Sumathi Kv
 
PPTX
Revisiting a data structures in detail with linked list stack and queue
ssuser7319f8
 
PPT
Chapter 5 ds
Hanif Durad
 
PPT
Unit ii(dsc++)
Durga Devi
 
PDF
Linked Lists.pdf
Kaynattariq1
 
PPTX
Linked list
akshat360
 
PPT
linked_lists.ppt linked_lists linked_lists
AmsaAzeem
 
PPTX
Data Structures_Linked List
ThenmozhiK5
 
PPT
17 linkedlist (1)
Himadri Sen Gupta
 
PPTX
UNIT 2LINKEDLISdddddddddddddddddddddddddddT.pptx
shesnasuneer
 
Linked List.pptx
PoonamPatil120
 
DS_LinkedList.pptx
msohail37
 
Algo>ADT list & linked list
Ain-ul-Moiz Khawaja
 
Lecture 3 List of Data Structures & Algorithms
haseebanjum2611
 
dynamicList.ppt
ssuser0be977
 
data structures lists operation of lists
muskans14
 
Linked list (1).pptx
rajveersingh643731
 
DSL Unit 4 (Linked list) (PPT)SE3rd sem sppu.pptx
vaibhavkore8
 
ds-lecture-4-171012041008 (1).pdf
KamranAli649587
 
Operations on linked list
Sumathi Kv
 
Revisiting a data structures in detail with linked list stack and queue
ssuser7319f8
 
Chapter 5 ds
Hanif Durad
 
Unit ii(dsc++)
Durga Devi
 
Linked Lists.pdf
Kaynattariq1
 
Linked list
akshat360
 
linked_lists.ppt linked_lists linked_lists
AmsaAzeem
 
Data Structures_Linked List
ThenmozhiK5
 
17 linkedlist (1)
Himadri Sen Gupta
 
UNIT 2LINKEDLISdddddddddddddddddddddddddddT.pptx
shesnasuneer
 
Ad

Recently uploaded (20)

PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PDF
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Ad

Linked lists a

  • 2. WHAT IS A LIST?  A list is a collection of items:  It can have an arbitrary length  Objects / elements can be inserted or removed at arbitrary locations in the list  A list can be traversed in order one item at a time 2
  • 3. LIST AS AN ADT  A list is a finite sequence (possibly empty) of elements with basic operations that vary from one application to another.  Basic operations commonly include:  Construction: Allocate and initialize a list object (usually empty)  Empty: Check if list is empty  Insert: Add an item to the list at any point  Delete: Remove an item from the list at any point  Traverse: Visiting each node of list 3
  • 4. VARIATIONS OF LINKED LISTS  Singly linked lists  Circular linked lists  Doubly linked lists  Circular doubly linked list 4
  • 5. LINKED LIST Minimal Requirements  Locate the first element  Given the location of any list element, find its successor  Determine if at the end of the list 5
  • 6. LINKED LIST TERMINOLOGIES  Traversal of List  Means to visit every element or node in the list beginning from first to last.  Predecessor and Successor  In the list of elements, for any location n, (n-1) is predecessor and (n+1) is successor  In other words, for any location n in the list, the left element is predecessor and the right element is successor.  Also, the first element does not have predecessor and the last element does not have successor. 6
  • 7. LINKED LISTS  A linked list is a series of connected nodes  Each node contains at least  A piece of data (any type)  Pointer to the next node in the list  Head: pointer to the first node  The last node points to NULL A  Head B C A data pointer node 7
  • 8. LISTS – ANOTHER PERSPECTIVE A list is a linear collection of varying length of homogeneous components. Homogeneous: All components are of the same type. Linear: Components are ordered in a line (hence called Linear linked lists). 8
  • 9. ARRAYS VS LISTS • Arrays are lists that have a fixed size in memory. • The programmer must keep track of the length of the array • No matter how many elements of the array are used in a program, the array has the same amount of allocated space. • Array elements are stored in successive memory locations. Also, order of elements stored in array is same logically and physically. 9
  • 10. • A linked list takes up only as much space in memory as is needed for the length of the list. • The list expands or contracts as you add or delete elements. • In linked list the elements are not stored in successive memory location • Elements can be added to (or deleted from) either end, or added to (or deleted from)the middle of the list. ARRAYS VS LISTS 10
  • 11. ARRAY VERSUS LINKED LISTS  Linked lists are more complex to code and manage than arrays, but they have some distinct advantages.  Dynamic: a linked list can easily grow and shrink in size.  We don’t need to know how many nodes will be in the list. They are created in memory as needed.  In contrast, the size of a C++ array is fixed at compilation time.  Easy and fast insertions and deletions  To insert or delete an element in an array, we need to copy to temporary variables to make room for new elements or close the gap caused by deleted elements.  With a linked list, no need to move other nodes. Only need to reset some pointers. 11
  • 13. BASIC OPERATIONS OF LINKED LIST  Linked List, a linear collection of data items, called nodes, where order is given y means of pointers.  Elements:  Each node is divided into two parts:  Information  Link ( pointing towards the next node)  (Common) Operations of Linked List  IsEmpty: determine whether or not the list is empty  InsertNode: insert a new node at a particular position  FindNode: find a node with a given value  DeleteNode: delete a node with a given value  DisplayList: print all the nodes in the list 13
  • 14. AN INTEGER LINKED LIST list 10 13 5 2 First Node of List data next NULL Last Node of List 14
  • 15. CREATING A LIST NODE p 10 struct Node { int data; // data in node Node *next; // Pointer to next node }; Node *p; p = new Node; p - > data = 10; p - > next = NULL; 15
  • 16. CREATING A LIST NODE p 10 class Node { public: int data; // data in node Node *next; // Pointer to next node }; Node *p; p = new Node; p - > data = 10; p - > next = NULL; 16 To avoid get/set methods
  • 17. THE NULL POINTER NULL is a special pointer value that does not reference any memory cell. If a pointer is not currently in use, it should be set to NULL so that one can determine that it is not pointing to a valid address: int *p; p = NULL; 17
  • 19. AN INTEGER (SINGLY) LINKED LIST list 10 13 5 2 First Node of List data next NULL Last Node of List class Node { public: int data; Node *next; }; Basic Concepts 19
  • 20. JOINING TWO NODES Node *p, *q; p = new Node; p - > data = 10; p - > next = NULL; q = new Node; q - > data = 6; q - > next = NULL; p - > next = q; p 10 q 6 6p 10 q Basic Concepts 20
  • 21. ACCESSING LIST DATA Expression p p - > data p - > next p - > next - > data p - > next - > next 6p 10 Node 1 Node 2 Value Pointer to first node (head) 10 Pointer to next node 6 NULL pointer Basic Concepts 21
  • 22. BUILDING A LIST FROM 1 TO N class Node { public: int data; Node *next; }; Node *head = NULL; // pointer to the list head Node *lastNodePtr = NULL; // pointer to last node head lastNodePtr Basic Concepts 23
  • 23. CREATING THE FIRST NODE Node *ptr; // declare a pointer to Node ptr = new Node; // create a new Node ptr - > data = 1; ptr - > next = NULL; head = ptr; // new node is first lastNodePtr = ptr; // and last node in list head 1 ptr lastNodePtr Basic Concepts 24
  • 24. ADDING MORE NODES for (int i = 2; i < = n; i ++ ) { ptr = new Node; ptr - > data = i; ptr - > next = NULL; lastNodePtr - > next = ptr; // order is lastNodePtr = ptr; // important } 2head 1 ptr lastNodePtr Basic Concepts 25
  • 25. 2head 1 ptr lastNodePtr 2head 1 ptr lastNodePtr 3 •Create a new node with data field set to 3 •Its next pointer should point to NULL Initially Basic Concepts 26
  • 26. 2head 1 ptr lastNodePtr 2head 1 ptr lastNodePtr 3 The next pointer of the node which was previously last should now point to newly created node “lastNodePtr->next=ptr” Basic Concepts 27
  • 27. 2head 1 ptr lastNodePtr 2head 1 ptr lastNodePtr 3 The next pointer of the node which was previously last should now point to newly created node “lastNodePtr->next=ptr” Basic Concepts 28
  • 28. 2head 1 ptr lastNodePtr 2head 1 ptr lastNodePtr 3 LastNodePtr should now point to the newly created Node “lastNodePtr = ptr;” Basic Concepts 29
  • 30. BASIC LINKED LIST OPERATIONS  Traversing through the list  Node Insertion  Insertion at the beginning of the list  Insertion at the end of the list  Insertion in the middle of the list  Node Deletion  Deletion at the beginning of the list  Deletion at the end of the list  Deletion from the middle of the list 31
  • 32. TRAVERSING THE LIST 33 ptr = first; while (ptr != null_value) { Process data part of node pointed to by ptr ptr = next part of node pointed to by ptr; }
  • 33. 34 9 17 22 26 34first ptr 9 17 22 26 34first ptr .. . 9 17 22 26 34first ptr 9 17 22 26 34first ptr ptr = first; while (ptr != null_value) { Process data part of node pointed to by ptr; ptr = next part of node pointed to by ptr; }
  • 34. TRAVERSING THE LIST 35 Node * currNode; currNode = head; while (currNode != NULL) { cout<< currNode->data; currNode = currNode->next; }
  • 35. NODE INSERTION  Insertion at the beginning of the list  Insertion at the end of the list  Insertion in the middle of the list 36
  • 36. NODE INSERTION AT THE BEGINNING Steps:  Create a node  Set the node data values  Connect the pointers 48 17 142head // Step 1 Step 2 Initial list List after Step 3 head 93
  • 37. NODE INSERTION AT THE BEGINNING 48 17 142head //Initial list head Node *ptr; ptr = new Node; ptr - > data = 93; ptr - > next = head; head = ptr; 93 head 93 Rearrange: ptr ptr head
  • 38. NODE INSERTION AT THE END Steps:  Create a Node  Set the node data values  Connect the pointers 48 17 142head // Step 1 Step 2 List after Step 3 Initial list
  • 39. NODE INSERTION AT THE END 48 17 142head //Initial list ptr Node * ptr; ptr = head; while (ptr->next != NULL) { ptr = ptr->next; } Need a pointer at the last node
  • 40. NODE INSERTION AT THE END 48 17 142head //Initial list ptr Node * p; p = new Node; p -> data = 150; p -> next = NULL; 150 // p
  • 41. NODE INSERTION AT THE END 48 17 142head ptr Node * p; p = new Node; p -> data = 150; p -> next = NULL; ptr -> next = p; 150 // p
  • 42. NODE INSERTION AT ARBITRARY POSITION Steps:  Create a Node  Set the node data values  Break pointer connection  Re-connect the pointers Step 1 Step 2 Step 3 Step 4
  • 43. NODE INSERTION AT ARBITRARY POSITION Steps:  Create a Node  Set the node data values  Break pointer connection  Re-connect the pointers Need a pointer on the node after which a new node is to be Inserted. For instance, if new node is to be inserted after the node having value ‘17’, we need a pointer at this node ptr How to get pointer on desired node?
  • 44. NODE INSERTION AT ARBITRARY POSITION Suppose we want to insert a node after the node having value ‘x’: ptr Node * ptr; ptr = head; while (ptr->data != x) { ptr = ptr->next; }
  • 45. NODE INSERTION AT ARBITRARY POSITION ptr Node * ptr; ptr = head; while (ptr->data != x) { ptr = ptr->next; } Node * p; p = new Node; p -> data = 100; p -> next = NULL; 150 // p
  • 46. NODE INSERTION AT ARBITRARY POSITION ptr Node * ptr; ptr = head; while (ptr->data != x) { ptr = ptr->next; } Node * p; p = new Node; p -> data = 150; p -> next = NULL; p -> next = ptr -> next; ptr -> next = p; 150 p
  • 47. NODE DELETION  Deleting from the beginning of the list  Deleting from the end of the list  Deleting from the middle of the list
  • 48. DELETING FROM THE BEGINNING Steps:  Break the pointer connection  Re-connect the nodes  Delete the node 4 17head 426 4 17 head 426 4 17head 42
  • 49. DELETING FROM THE BEGINNING 4 17 head 426 head 4 17 426 4 17head 42 Node * ptr; ptr = head; head = head ->next; delete ptr; ptr ptr head
  • 50. DELETING FROM THE END Steps:  Break the pointer connection  Set previous node pointer to NULL  Delete the node 4 17head 426 4 17head 426 4 176head
  • 51. DELETING FROM THE END 4 17head 426 We need a pointer one node before the node to be deleted predPtr Node * ptr; Node * predPtr; ptr = head; predPtr = NULL; while (ptr->next != NULL) { predPtr = ptr; ptr = ptr->next; } ptr
  • 52. DELETING FROM THE END 4 176head predPtr -> next = NULL; delete ptr; 4 17head 426 predPtr ptr 4 17head 426 predPtr ptr 4 17head 426 predPtr ptr
  • 53. DELETING FROM AN ARBITRARY POSITION Steps:  Set previous Node pointer to next node  Break Node pointer connection  Delete the node 4 17 42head 4 17head 42 4head 42
  • 54. DELETING FROM AN ARBITRARY POSITION 4 17 42head We need a pointer on the node to be deleted (as well a pointer to one node before the node to be deleted) predPtr ptr Node * ptr; Node * predPtr; ptr = head; predPtr = NULL; while (ptr->data != x) { predPtr = ptr; ptr = ptr->next; } Given the value of the node to be deleted, assume this to be variable ‘x’ Keep moving a pointer until the required node is reached
  • 55. DELETING FROM AN ARBITRARY POSITION 4 17 42head predPtr ptr predPtr -> next = ptr -> next; delete ptr; 4 17 42head predPtr ptr 4 17 42head predPtr ptr
  • 56. PROS AND CONS OF LINKED LISTS • Access any item as long as external link to first item maintained • Insert new item without shifting • Delete existing item without shifting • Can expand/contract as necessary • Overhead of links: used only internally, pure overhead • No longer have direct access to each element of the list • We must go through first element, and then second, and then third, etc. 57