Lecture 7 & 8 & 9: Halabja University Collage of Science /Computer Science Department 2020-2021 Karwan Mahdi [email protected] Data Structures & Algorithms Linked List(Circular) &Doubly Linked List (Circular)& Multi list
Lecture 7 & 8 & 9:
Halabja University
Collage of Science /Computer Science Department
2020-2021
Karwan [email protected]
Data Structures & Algorithms
Linked List(Circular) &Doubly Linked List(Circular)& Multi list
Understand the basic concept and architecture of linked list
Understand the algorithms for insertion, deletion, traversal and sorting operation
Difference between linked lists and arrays.
Describe the relative advantages and disadvantages of linked list
Objectives
Understand the concept and structure of circular linked list, doubly linked list and multi-lists
Learn about the basic operations associated with different forms of the linked lists
Understand the implementation aspects of circular linked list and doubly linked lists
Learn about the structure and advantages of multi-lists
A linked list is a collection of data elements called node.
Each node consists of two parts called information field and link field
First field normally contains data elements, usually primitive type
Link field distinguish a linked list from other data structure.
First element in the list in referred to as front node or head node.
Elements are traversed by first accessing the head pointer, and then moving to successor nodes
In an empty list head pointer is set to null value.
Last element is called tail node or end node
The link pointer of tail node contains a symbolic constant Null to mark the end of the list
Introduction
Introduction• A linked list is a group of items arranged in a linear order. it is a flexible dynamic data structure.
• Linked lists are non-contiguous. it can grow or shrink in size as the program runs.
• Figure shows two such lists
• First figure shows a linked list of same letter words
• Second example shows linked list of records
CAT RAT MAT FAT ✖
150 HARDI COMP 252 ARY CHEM
300 ALI BIO 295 KAWA PHYS ✖
There are two type of linked list: (both are in linear or circular)
Single linked list
Doubly linked list
Linked Lists
Nodes Nodes are used to store data.
A node contains:
Data: one or more data fields.
Link: is the pointer (reference) to the next node (address) if exists, otherwise it is null.
Stores Address of the next node
Stores the Actual value
Most applications of linked list require
• Inserting of new data elements
• Deleting the existing data
• Printing the contents of a list
• Traversing the list to access each node
• Sorting the list in the alphabetic or numeric
• Searching for a given data value in the list
Operation on Linked Lists
Other less frequently used operations include
• Checking the size of a linked list
• Checking if the list is empty
• Copying elements of a list into another list
• Normally the operation of checking for “the list is full” is not applied, because
a linked list can grow dynamically.
Inserting Nodes Into a Linked list • A new node can be inserted (at the beginning, in the middle, and at the end)
• Inserting a new node at the front following procedure is occur
• Front is identified by head pointer
• Its link pointer is set so that it points to the new node
• New node is linked to the previous front
Algorithm insertFirst(value)Insert new data to the beginning of the list:
1.Declare a new node first
2.If head = null then {First check is list exists or we have to create it.}
3.head ←new node(value)
4.head.next←null
5.End if
6.Else first ←new node(value)
7.first.data←value
8.first.next←head
9.head ←first
10.End else.
11.End insertFirst.
first
first
Inserting Nodes Into a Linked list
• Inserting a new node at the End of the list
• Pointer is used, which is set to point to the first node
• Then list is traversed until the last node is reached
• A new node is created
• Link pointer of tail node of original list is reset to point to new node
9
Algorithm insertLast(value)
Insert new data to the end of the list:
1.Allocate two new node tail, add.
2.If head = null then. {First check is link exist or we have to create it }
3.head ←new node(value).
4.head.next←null.
5.Else tail ←head
6.While tail.next!= null do:
7.tail ←tail.next
8.add ←new node(value).
9.add.next←null
10.tail.next←add
11.End else.
12.End insertLast.
Inserting Nodes Into a Linked list
Inserting a new node at the Middle of the list
• New node can be inserted which either precedes or succeeds a given node
• To insert a middle node following steps are taken
• A temporary pointer is used to traverse the list
• A new node is created
• Linked pointer is reset to point to the new node
• Link pointer of new node is reset to point to the successor node
Algorithm addPosition(pos, value)
Insert a new node to a specific position in the list:
1.Declare two new nodes count, add.
2.for i←1, count ←head, i< pos, increment i do:
3.count ←count.next.
4.if count = null {check if that position exist or not}
5.Print the number of your position must be less than the linked list.
6.Return.
7.End if.
8.End for.
9.add ←new node (value).
10.add.next←count.next.
11.count.next←add.
12.End addPosition.
Deleting Nodes From a Linked list • A major advantages of linked list is that nodes can be easily removed
• Deletion can be performed to remove node (at the front, in the middle, and at the tail node)
• Deleting a front node
• We create a pointer which identifies the first node
• Head pointer is then reset to point to the next node
• Using the pointer we remove the first node
Algorithm deleteFirst()
Delete the first element from the list:
1.If isEmpty{First check is link exist}
2.Then Print the link is empty.
3.Else Node temp ←head {allocate a temporary node.}
4.head ←head.next
it mean(head ←head.getNext( ))
make head point to next node(or null)
5.temp ←null
it mean(temp.setNext(null))
null out the next pointer of the removed node
size ← size-1(decrement the node count
6.End of else
7.End of deleteFirst
Deleting Nodes From a Linked list
Deleting a tail node
• To remove the tail node two pointers are used
• First pointer points to tail node
• Second pointer points to node that precedes that tail node
• Using second pointer link pointer of the node is point to Null
• Then using first pointer to remove tail node
Deleting Nodes From a Linked list
Deleting a middle node
• To remove the middle node two pointers are used
• After the node has been identified by first pointer, its link with the next node is deleted
• Using second pointer, link pointer is set to point to the successor node
• Using first pointer the specified node is deleted
Algorithm deleteValue(element)
Delete specified node from the list:
1.Declare two new nodes move, add.
2.move ←head.
3.If move.data= element
4.head ←move.next.
5.move ←null.
6.Return.
7.End if.
add ←move.
9.move ←move.next.
10.While move != null do:
11.if move.data= element
12.add.next←move.next.
13.move ←null.
14.Return.
15.End if.
16.add ←move.
17.move ←move.next..
18.End while
19.Print the element not found.
20.End deleteValue.
• In traversing each node is visited exactly once.
• Traversing is performed when we need to access information contained in each of the
node, for example, to print the list or to determine size of the list
• Briefly traversal is conducted as follows:
• A pointer is set to point to the first node
• After the data has been extracted from the current node, the pointer is moved to
the next node
• This procedure is repeated until a node with NULL pointer
• We can not traverse it from last, it is possible only from the beginning.
Traversing a Linked List
• In Sorting a list, we compare the contents of nodes and swap them if necessary
• Remember: only the contents of nodes are swapped. The link pointer of corresponding
nodes remain unchanged
Sorting Linked List
• To perform linear search, we start with the first element of the list
• Then compare the contents of nodes with value to be searched for
• If the list is sorted, the search process can a abandoned if a node contains valuegreater than the search value
• If list in not already sorted, the list should be scanned up to tail node
Searching Linked List
• Linked lists are frequently used to implement other data structure such as tree, and graphs
• Linked lists are useful for creating dynamic stacks and queues which can grow or shrink at run time
• Linked lists can be used to store and process polynomials
Application of Linked List
• To examine time efficiency, we assume a list consists of N nodes
• In insertion and deletion operations information portion is not affected, only link
pointer are modified
• The resetting of link pointers is not an expensive operation
• Therefore, the time efficiency depends on the number of times the list nodes are traversed
• When a node is inserted at the front , only the first node is examined
• Insertion of front node has running time O(1)
• If a node is inserted at end, nodes would need to be scanned N times
• Running time of operation for inserting a tail node is O(N)
Performance of Linked List Operations
• If middle node is inserted, on an average N/2 comparisons of the link parts will be made
• Efficiency is O(N/2) or equivalently O(N)
• In sorting list, we use two nested loops
• Sort operation has time efficiency O(N2)
Performance of Linked List Operations
• In deletion operation, two pointer are used, as such two comparisons are made
• To delete the tail node, the current and succeeding nodes are examined
• Deletion of tail node has efficiency O(2N) or simply O(N)
Arrays or Linked Lists?
Neither arrays nor linked lists are best; it depends on:
What you're going to do most:
◦If the problem involves many accesses to the information. Then it should be stored in an Array.
◦If problem involves many insertions and deletions not at end. Information should be stored in LinkedList.
What your priorities are: (Time or space?)
Algorithm printList()Print all elements in the list:
1.Node currentNode←head {Declare new node}
2.While currentNode!= null
3.Print currentNode.data.
4.currentNode←currentNode.next.
5.End while
6.End printList.
Advantages of Linked List• Size of storage space can be adjusted dynamically at run time
• Insertion and deletion operations are comparatively fast
• List traversal is extremely fast
• space is not wasted.
• It does not need shifting elements for insertion and deletion.
Disadvantages of Linked List• There is an overhead of pointers which occupy additional storage
• Elements of a linked can not be accessed directly
• Searching is a costly operation. Efficient sorting methods such as binary search can
not be applied to a linked list
• Different amount of time is required to access each element.
• If we want to access a particular element, we have to go through all the elements that
come before that element.
Linked list support the following operation:
1) insertFirst(obj): Insert an element obj at the beginning of the list.
2) insertLast(obj): Add element obj at the end of linked list.
3) addPosition(obj, p): Add element at position p.
4) objdeletFirst( ): Delete the first element from the linked list.
5) deleteValue(obj):Delete obj from the list.
6) isEmpty( ): Return true if list is empty, else return false.
7) size( ):Return the number of elements remain in the list.
Linked List ADT
Student Work 4: convert the Implementation of Linked List Slide(Next slide) to java code
by using the previous operation algorithms(previous slides).
Implementation of Linked List
1.Create a class for node as template: 1.create class Node:
2.Declare data part data.
3.Declare pointer( reference )node next.
4.Create constructor Node(value):
5.Initialize data ←vlaue.
6.end constructor.
7.end of class.
2.Create class for linked list : 1.Create class for MyLinkedList
2.Allocate a node head.
3.Create constructor MyLinkedList( ):
4.Assign head ←null. {the link is empty}
5.end constructor.
6.Create method isEmpty( ), insertFirst( ), deletFirst( ), printList( ), insertLast( ), addPosition( ), deleteValue( ).
7.end of class.
Variation of Linked list
• There are several variation of regular linked list. Some common types are:
1) Circular Linked Lists
2) Doubly Linked Lists
3) Circular Doubly Linked Lists
4) List containing multiple linked lists, commonly referred to as multi list
• In a regular linked list we can not go to any the preceding nodes
• A circular linked list overcomes this limitation
• In a circular linked list, the pointer in the tail node points to the front node
• The list has no front or tail node. To make entry into the circular linked list a
reference node is used which is identified by an external pointer
• In regular list, this pointer is referred to as head pointer
Circular(single)Linked Lists
A B C D E
Application of Circular Linked List• Circular lists are useful in applications to repeatedly go around the list.
• For example, when multiple applications are running on a PC, it is common for the
operating system to put the running applications on a list and then to cycle through
them, giving each of them a slice of time to execute, and then making them wait
while the CPU is given to another application
• Circular linked lists have some advantages over regular linked list
• Any node can be designated as the first node
• Each node is accessible from any other node
• A circular linked list is particularly suited to process strings
• Limitation is that:
• Unless starting node is identified, traversal of circular list might go into an infinite loop
Advantages and Disadvantages of Circular Linked List
• Doubly Linked List is a collection of nodes where each node contains one or more
data fields, it also references to next node and previous node.
• The next pointer of the last node points to a NULL reference and the previous
pointer of first node points to NULL to indicate the end of the list in both ways
Doubly Linked List
• Basic operation include insertion, deletion, traversal, sorting and searching.
• Unlike a regular list, we can traverse in forward and backward directions. In
other words we can perform bi-direction traversals
• Insertion and deletion can be performed by adjusting left and right link pointer
Basic Operation on Doubly Linked List
Nodes in Doubly LL Nodes are used to store data.
A node contains:
Data: one or more data fields.
next: is the pointer to the next node if exists, otherwise it is null.
prev: is the pointer to the previous node if exists, otherwise it is null.
Doubly Linked List Implementation –Node Class
Create a class for Node as a template:
1.Initialize data part data.
2.Initialize pointer Node next.
3.Initialize pointer Node prev.
4.Declare constructor Node(newData):
5.data ←newData.
6.End constructor.
7.End of class. Doubly Linked List Implementation –Double Linked List Class
Create a class for DoublyLinkedList:
1.Allocate two nodes head and tail.
2.Declare constructor DoublyLinkedList():
3.Assign head ←tail ←null {it shows the list is empty}
4.End constructor.
5.Add other methods that you need, for operations of the linked list.
6.End class
Algorithm insertFirst(value)
Insert new data to the beginning of the DLL:
1.Node current←new Node(value)
2.If isEmpty
3.head ←tail ←current
4.Else
5.current.next←head
6.head.prev←current
7.head ←current
8.End else
9.End insertFirst
Showing Algorithm insertFirst(value) in other way
Algorithm insertLast(value)
Insert new data to the end of the list:
1.Node current ←new node(value)
2.If isEmpty
3.head ←tail ←current
4.Else
5.current.prev←tail
6.tail.next←current
7.tail ←current
8.End else
9.End insertLast.
Inserting a Node into Doubly Linked List• Node can be inserted at front, in the middle or at the tail
• Procedure for front or tail is similar to one for the regular linked list
• To insert in the middle we use a pair of temporary pointers
Figure illustrates the insertion of a middle node
Algorithm deleteFirst( )
Delete the first element from the list:
1.Node temp ←head
2.If isEmpty
3.Print the list is empty
4.Else
5.head.next.prev←null
6.head ←head.next
7.temp ←null
8.End Else
9.End deleteFirst.
What happens if the list contains only one node?
1
2
Algorithm deleteLast( )
Delete the last element from the list:
1.Node temp←tail
2.If isEmpty
3.Print the list is empty
4.Else
5.tail.prev.next←null
6.tail ←tail.prev
7.temp ←null
8.End else
9.End deleteLast
What happens if the list contains only one node?
1
2
• In order to delete a node, we first identify the node using a temporary pointer
• Then the link pointers of succeeding and preceding nodes are adjusted to bypass the
node to be deleted
Deleting a Node from a Doubly Linked List
Algorithm deleteValue(key)Delete specified value from the list:
1.Allocate node current
2.current ←head
3.While current.data not equal key
4.current ←current.next
5.if current = null then
6.return false
7.End if
8.End while
9.If current = head then {if element is the first}
10.head ←current.next
11.current.next.prev ←null
12.Else if current = tail {if element is the last}
13.tail ←current.prev
14.tail.next ←null
15.Else {if element in the middle jump}
16.current.prev.next = current.next
17.current.next.prev = current.prev
18.End if
19.Return 1
20.End deleteValue
Showing Algorithm deleteValue(key) in detail
Algorithm displayForward()
Print nodes of the list from first one to the last
1.Allocate node current ←head {start at the beginning}
2.while current not equal to null
3.print current.data
4.current ←current.next{move to next link}
5.End while
6.End displayForward.
What if we want to print values of the list backwards (i.e. from last to the first)?
• In particular inserting or deleting at the end of the list takes O(1) time for doubly
linked lists and O(n) time for singly linked lists.
• Inserting or deleting at the front of the list takes O(1) time for doubly linked lists
and singly linked lists
Performance of Doubly Linked List Operations
Algorithm addPosition(pos, value)Insert new node to a specific position in the list:
1.Allocate Node count, current
2.For I ←1, count ←head, i less than pos , increment i
3.count ←count.next
4.If count = null
5.Print number of position must be less than your LL
6.Return
7.End if
8.End for
9.current ←new node(value)
10.current.prev ←count
11.current.next ←count.next
12.count.next ←current
13.count.next.prev ←current
14.End addPosition
With this algorithm, What happens if you want to add the new value:
1.When the list is empty?
2.To the start of the list?
3.To the end of the list?
Main advantages are:
• It allows a bidirectional traversal
• Insertion and deletion are fast
• Sorted list can printed in ascending and descending order
Major drawbacks are:
• Additional storage space is required for the link pointers
• Address of preceding and succeeding nodes needs to be closely tracked
• List manipulations are slower (because more links must be changed).
• Greater chance of having bugs.
Advantages and Disadvantages of Doubly Linked List
• It is variant of the doubly linked list
• In this case next pointer in the tail node contains pointer to the first element
• Previous link pointer in the first node points to the tail node
• The forward (next) pointer of the last node points to the first node (head), and, the
backward (prev) pointer of the first node points to the last node.
Circular Doubly Linked List
• Since no first and last nodes are defined, we can choose an arbitrary node as the head node
• A circular doubly linked list has all the advantages of circular and doubly linked list
• Its main disadvantage is that link pointers need to be closely monitored; otherwise,
traversal can lead to infinite loop
• We can combine a set of related list structures into an integrated list called multi-list
• In multi-lists nodes of all the integrated list can be accessed using link pointer
• For example, a list that contains student records and another list that contains subjects can be
into a single multi-list
• We can, for example, access all students that are registered in a given subject
• Conversely, we can access the subjects in which a particular student is registered
Multi Lists
• To build the multi-list we need additional link node. Thus multi-list contains:
• Nodes that contain subject data and link pointers to subjects
• Nodes that contain student data and link pointers to students
• Link nodes that connect subjects with students
Student Work 5: use the previous operation algorithms(previous slides) to implement the
doubly Linked Lists.
Example of Multi Lists
Sub 1 Sub 2 Sub 3 Sub 4
Std 1 1 1 1 3
Std 2 2 2 2 3
Std 3 3 2 3 4
Std 4 4 1 4 4
Std 5 4 2 5 4
"Data Structures & Algorithms in Java", Robert Lafore, second ed., 2003.
http://www.c4learn.com/data-structure/linked-list-disadvantages/
http://www.java2novice.com/data-structures-in-java/linked-list/doubly-linked-list/
"Data Structures and Algorithms in Java", Michael T. Goodrich and Roberto
Tamassia, 4th ed.
Several slides from (Mihran A. Muhammed--Polytechnic University of Sulaimani)
Reference