Sie sind auf Seite 1von 104

Linked Lists

Linked Lists / Slide 2

List Overview
 Linked lists
 Abstract data type (ADT)
 Basic operations of linked lists
 Insert, find, delete, print, etc.
 Variations of linked lists
 Circular linked lists
 Doubly linked lists
Linked Lists / Slide 3

List Operations

Useful operations
 createList(): create a new list (presumably empty)
 copy(): set one list to be a copy of another
 clear(); clear a list (remove all elements)
 insert(X, ?): Insert element X at a particular position
in the list
 remove(?): Remove element at some position in
the list
 get(?): Get element at a given position
 update(X, ?): replace the element at a given position
with X
 find(X): determine if the element X is in the list
 length(): return the length of the list.
Linked Lists / Slide 4

List Operations
 We need to decide what is meant by “particular
position”; we have used “?” for this.

 There are two possibilities:

1. Use the actual index of element: insert after element


3, get element number 6. This approach is taken by
arrays
2. Use a “current” marker or pointer to refer to a
particular position in the list.
Linked Lists / Slide 5

List Operations
 If we use the “current” marker, the following
four methods would be useful:

 start(): moves “current” pointer to the very first


element.
 tail(): moves “current” pointer to the very last
element.
 next(): move the current position forward one
element
 back(): move the current position backward one
element
Linked Lists / Slide 6

Implementing Lists
 We have designed the interface for the List; we
now must consider how to implement that
interface.
 Implementing Lists using an array: for example,
the list of integers (2, 6, 8, 7, 1) could be
represented as:

current size
A 2 6 8 7 1
3 5
1 2 3 4 5
Linked Lists / Slide 7

List Implementation
 insert(9,3); current position is 3. The new list would
thus be: (2, 6, 8, 9, 7, 1)
 We will need to shift everything to the right of 8 one
place to the right to make place for the new element ‘9’.

current size
step 1: A 2 6 8 7 1
3 5
1 2 3 4 5 6

step 2: A current size


2 6 8 9 7 1
4 6
1 2 3 4 5 6

notice: current points


to new element
Linked Lists / Slide 8

Implementing Lists
 next():
current size
A 2 6 8 9 7 1
4 6
1 2 3 4 5 6 5
Linked Lists / Slide 9

Implementing Lists

 There are special cases for positioning the


current pointer: (boundary conditions)
a. past the last array cell
b. before the first cell

 We will have to worry about these when we


write the actual code.
Linked Lists / Slide 10

Implementing Lists
 remove(): removes the element at the current
index
current size
Step 1: A 2 6 8 9 1
5 6
1 2 3 4 5 6
5

current size
Step 2: A 2 6 8 9 1
5 5
1 2 3 4 5

 We fill the blank spot left by the removal of 7 by


shifting the values to the right of position 5 over to the
left one space.
Linked Lists / Slide 11

Implementing Lists
find(X): traverse the array until X is located.

int find(int X)
{
int j;
for(j=1; j <= size; j++ )
if( A[j] == X )
break;

if( j < size+1 ) { // found X


current = j; // current points to where X found
return 1; // 1 for true
}
return 0; // 0 (false) indicates not found
}
Linked Lists / Slide 12

Implementing Lists
 Other operations:

get()  return A[current];


update(X)  A[current] = X;
length()  return size;
back()  current--;
start()  current = 1;
end()  current = size;
Linked Lists / Slide 13

Analysis of Array Lists


 insert
 we have to move every element to the right of
current to make space for the new element.
 Worst-case is when we insert at the beginning; we
have to move every element right one place.
 Average-case: on average we may have to move
half of the elements
Linked Lists / Slide 14

Analysis of Array Lists


 remove
 Worst-case: remove at the beginning, must shift all
remaining elements to the left.
 Average-case: expect to move half of the elements.

 find
 Worst-case: may have to search the entire array
 Average-case: search at most half the array.

 Other operations are one-step.


Linked Lists / Slide 15

List Using Linked Memory


 Various cells of memory are not allocated
consecutively in memory.
 Not enough to store the elements of the list.
 With arrays, the second element was right next
to the first element.
 Now the first element must explicitly tell us
where to look for the second element.
 Do this by holding the memory address of the
second element
Linked Lists / Slide 16

Linked List
 A linked list is a data structure that can store an indefinite amount of
items.
 These items are connected using pointers in a sequential manner.
 There are two types of linked list:
1. Singly-linked list
2. Doubly-linked list
Linked Lists / Slide 17

Nodes
 The elements of a linked list are called
the nodes.
A node has two fields
• Data
• Next
• The data field contains the data being
stored in that specific node. It cannot just
be a single variable. There may be many
variables presenting the data section of a
node. The next field contains the address
of the next node. So this is the place
where the link between nodes is
established.
Linked Lists / Slide 18

 No matter how many nodes are present in the


linked list, the very first node is
called head and the last node is called
the tail. If there is just one node created then
it is called both head and tail.
Linked Lists / Slide 19

Implementation of Linked List


linked list consists of nodes, Need to declare a
structure which defines a single node. Our
structure should have at least one variable for
data section and a pointer for the next node. In
C++, our code would look like this:
struct node
{
int data;
node *next;
};
Linked Lists / Slide 20

Creation of Linked List


 Class which will contain the functions to handle the nodes. This
class should have two important pointers, i.e. head and tail. The
constructer will make them NULL to avoid any garbage value.

class list
{
Private:
node *head, *tail;
public:
list()
{
head=NULL;
tail=NULL;
}
};
Linked Lists / Slide 21

Node creation
 Need a pointer of a node type
 Insert the value in its data field
 Next field of node would be declared as NULL
 If the linked list is still empty
 It means if the head is equal to NULL then we
can conclude that the linked list is empty.
 If there is just one node  in linked lists, then it
is called both head and tail.
Linked Lists / Slide 22

  if a linked list is created already


 insert node at the end of the linked list
 create this newly created node next to a tail node
 The creation of a new node at the end of
linked list has 2 steps:
1. Linking the newly created node with tail node.
Means passing the address of a new node to the
next pointer of a tail node.
2. The tail pointer should always point to the last
node. So we will make our tail pointer equal to a
new node.
Linked Lists / Slide 23

 Creation of new a node


void createnode(int value)
{
node *temp=new node;
temp->data=value;
temp->next=NULL;
if(head==NULL)
{
head=temp;
tail=temp;
}
else
{
tail->next=temp;
tail=temp;
}
}
Linked Lists / Slide 24

Displaying Linked List 

void display()
{
node *temp=new node;
temp=head;
while(temp!=NULL)
{
cout<<temp->data<<"\t";
temp=temp->next;
}
}
Linked Lists / Slide 25

Both createnode() and display() functions would be


written under public section of class.

The basic framework of a singly-linked list is ready. Now it


is the time to perform some other operations on the list.
Basically, two operations are performed on linked lists:

Insertion
Deletion
Linked Lists / Slide 26

INSERTION
Inserting a new node in the linked list is called
insertion.
A new node is created and inserted in the linked
list.
There are three cases considered while inserting a
node:
Insertion at the start
Insertion at the end
Insertion at a particular position
Linked Lists / Slide 27

Insert Noda at the start

Insertion of a new node is quite simple. It is just a 2-step


algorithm which is performed to insert a node at the start of a
singly linked list.
1.New node should be connected to the first node, which
means the head. This can be achieved by putting the address
of the head in the next field of the new node.

2.New node should be considered as a head. It can be


achieved by declaring head equals to a new node.

New_node next=head;
Head=new_node;
Linked Lists / Slide 28

The diagrammatic demonstration of


this process is given below:
Linked Lists / Slide 29

void insert_start(int value)


{
node *temp=new node;
temp->data=value;
temp->next=head;
head=temp;
}
Linked Lists / Slide 30

Insert node in the middle

While(P!=insert _position)
{
P=P next;
}
Store_next=p next;
P next=new_node;
New_node next=store_next;
Linked Lists / Slide 31

Insertion at Particular Position

 The new node can be inserted between the


previous and current node by just performing
two steps:
1. Pass the address of the new node in the next
field of the previous node.
2. Pass the address of the current node in the
next field of the new node.
Linked Lists / Slide 32

void insert_position(int pos, int value)


{
node *pre=new node;
node *cur=new node;
node *temp=new node;
cur=head;
for(int i=1;i<pos;i++)
{
pre=cur;
cur=cur->next;
}
temp->data=value;
pre->next=temp;
temp->next=cur;
}
Linked Lists / Slide 33

Insert a node at the end

While(P next!=null)
{
P=P next;
}
P next=new_node;
New_node next=null;
Linked Lists / Slide 34

Insertion at the End

The insertion of a node at the end of a linked list


is the same as we have done in node creation
function. If you noticed then, we inserted the
newly created node at the end of the linked list.
So this process is the same.
Linked Lists / Slide 35

DELETION

The basic structure is to declare a temporary


pointer which points the node to be deleted.
There are also three cases in which a node can
be deleted:
1.Deletion at the start
2.Deletion at the end
3.Deletion at a particular position
Linked Lists / Slide 36

Deletion at the Start


 In this case, the first node of the linked list is deleted. I
know, you remember that the first node is called the head.
So, we are going to delete the head node. The process of
deletion includes:
 Declare a temp pointer and pass the address of the first
node, i.e. head to this pointer.
 Declare the second node of the list as head as it will be the
first node of linked list after deletion.
 Delete the temp node.
Linked Lists / Slide 37

void delete_first()
{
node *temp=new node;
temp=head;
head=head->next;
delete temp;
}
Linked Lists / Slide 38

Deletion at the End


Deletion of the last node is a bit difficult to understand than the first
node. In the case of the first node, you just need access to the head
and you can delete it. But in the case of the last node, you also need
access to the second to the last node of the linked list as you will
delete the last node and make the previous node as the tail of linked
list.

Our algorithm should be capable of finding a node that comes before the last node.
This can be achieved by traversing the linked list. We would make two temporary
pointers and let them move through the whole linked list. At the end, the previous
node will point to the second to the last node and the current node will point to the
last node, i.e. node to be deleted. We would delete this node and make the previous
node as the tail.
Linked Lists / Slide 39

void delete_last()
{
node *current=new node;
node *previous=new node;
current=head;
while(current->next!=NULL)
{
previous=current;
current=current->next;
}
tail=previous;
previous->next=NULL;
delete current;
}
Linked Lists / Slide 40
Deletion at a Particular
Position
In linked list, we can delete a specific node. The process
of deletion is simple. Here we don’t use the head and tail
nodes. We ask the user to input the position of the node
to be deleted. After that, we just move two temporary
pointers through the linked list until we reach our specific
node. Now, we delete our current node and pass the
address of the node after it to the previous pointer. This
way, the current node is removed from the linked list and
the link is established between its previous and next
node.
Linked Lists / Slide 41

void delete_position(int pos)


{
node *current=new node;
node *previous=new node;
current=head;
for(int i=1;i<pos;i++)
{
previous=current;
current=current->next;
}
previous->next=current->next;
delete(current);
}
Linked Lists / Slide 42

Deleting a node in single link list

1. Starting node
2. Ending node
3. Internal node
Linked Lists / Slide 43

node *delete(node else


*head, char d) {
{ while(p data!=d)
node *p, *q; {
q=head; P=P next;
p=head next; q=q next;
if(q=data==d)//start node }
{ if(p next==null)//Last Node
head=p; {
delete(q); q next=null;
} delete(p);
}
Linked Lists / Slide 44

else
{
q next=p next; // internal node
delete(p);
}
}
return head;
}
Linked Lists / Slide 45

Find middle of a link list


node *find_middle(node *head)
node *p,*q;
p=head;
q=head;
while(q&&q next)
{
p=p next;
q=q next next;
}
return p;
}
Linked Lists / Slide 46

Search an element in a link list


void search(char s, node *head)
{
node *p=head;
while(p!=null)
{
if(p data==s)
{
cout<<“Elements found”;
break;
}
p=p next;
}
Linked Lists / Slide 47

Search an element in a linked


list(Iterative and Recursive)
Write a function that searches a given key ‘x’ in a
given singly linked list. The function should return
true if x is present in linked list and false otherwise.

For example:
Input:14,21,11,30,10
If key to be search is 15 then the function should
return false.
If key to be search is 14, then the function should
return true.
Linked Lists / Slide 48

Iterative Algorithm

1. Initialize a node pointer current=head


2. Do the following while current is not NULL
a) If current key is equal to the key
being searched, return true.
b) Current=current next
3. Return false.
Linked Lists / Slide 49
Linked Lists / Slide 50

C++ implementation of
iterative function
\* check whether the value x is present in linked list */
bool search(struct node* head, int x)
{
struct node* current=head; //initialize current
while(current!=NULL)
{
if(current key==x)
return true;
current=current next;
}
return false;
}
Linked Lists / Slide 51

Recursive Algorithm

bool search(head, x)
1.If head is NULL, return false
2.If head’s key is same as x, return true
3.Else return search(head next,x)
Linked Lists / Slide 52
Linked Lists / Slide 53
Linked Lists / Slide 54

/* checks whether the value x is present in linked list */


bool search (struct node* head, int x)
{
// Base case
if (head == NULL)
return false;
// if key is present in current node, return true
if (head key == x)
return true;
// recur for remaining list

return search(head next, x);


}
Linked Lists / Slide 55

Find the length of link list

cnt=0;
while(p!=null)
{
cnt=cnt+1;
p=p next;
}
Linked Lists / Slide 56

Traverse link list

void traverse(node *head)


{
node *p=head;
while(p!=null)
{
cout<<p data,
p=p next;
}
}
Linked Lists / Slide 57

Reverse a linked List


Linked Lists / Slide 58

Linked List
 Picture of our list (2, 6, 7, 8, 1) stored as a
linked list:

head

2 6 8 7 1 size=5

current
Linked Lists / Slide 59

Linked List
Note some features of the list:
 Need a head to point to the first node of the list.
Otherwise we won’t know where the start of the
list is.
 The current here is a pointer, not an index.
 The next field in the last node points to nothing.
We will place the memory address NULL which
is guaranteed to be inaccessible.
Linked Lists / Slide 60

Linked List
 Actual picture in memory:
1051 6
1052 1063
current 1053 1063
1054 2
head 1055 1051
1056
2 6 8 7 1 1057 7
1058 1060
current 1059
1060 1
1061 0
head 1062 1054
1063 8
1064 1057
1065
Linked Lists / Slide 61

Analysis of Linked List


 add
• we simply insert the new node after the current
node. So add is a one-step operation.
 remove
 remove is also a one-step operation
 find
 worst-case: may have to search the entire list
 back
 moving the current pointer back one node
requires traversing the list from the start until
the node whose next pointer points to current
node.
Linked Lists / Slide 62

Doubly-linked List
 Moving forward in a singly-linked list is easy;
moving backwards is not so easy.
 To move back one node, we have to start at
the head of the singly-linked list and move
forward until the node before the current.
 To avoid this we can use two pointers in a
node: one to point to next node and another to
point to the previous node:

prev element next


Linked Lists / Slide 63

Doubly-Linked List Node


class Node {
public:
int get() { return object; };
void set(int object) { this->object = object; };

Node* getNext() { return nextNode; };


void setNext(Node* nextNode)
{ this->nextNode = nextNode; };
Node* getPrev() { return prevNode; };
 void setPrev(Node* prevNode)
{ this->prevNode = prevNode; };
private:
int object;
Node* nextNode;
 Node* prevNode;
};
Linked Lists / Slide 64

64 AL
Linked Lists / Slide 65

Doubly-linked List
 Need to be more careful when adding or
removing a node.
 Consider add: the order in which pointers are
reorganized is important:

head 2 6 8 7 1 size=5

current
Linked Lists / Slide 66

In the next step, a programmer points the prevNode of the newNode to the node with
value 6.
newNode->setprev( current );

66 AL
Linked Lists / Slide 67

In the fourth step, the nextNode of the node with value 6 is pointing to the newNode i.e.
the node with value 9. Point the current to the newNode and add one to the size of the list
current->setNext( newNode );
current = newNode;
size++;

Now the
67 newNode has been inserted between
AL node with value 6 and node with value 8.
Linked Lists / Slide 68

Doubly-linked List
1. newNode->setNext( current->getNext() );

current

head 2 6 8 7 1 size=5

newNode 9 1
Linked Lists / Slide 69

Doubly-linked List
1. newNode->setNext( current->getNext() );
2. newNode->setprev( current );

current

head 2 6 8 7 1 size=5

newNode 9 1
Linked Lists / Slide 70

Doubly-linked List
1. newNode->setNext( current->getNext() );
2. newNode->setprev( current );
3. (current->getNext())->setPrev(newNode);

current

head 2 6 8 7 1 size=5

2 3

newNode 9 1
Linked Lists / Slide 71

Doubly-linked List
1. newNode->setNext( current->getNext() );
2. newNode->setprev( current );
3. (current->getNext())->setPrev(newNode);
4. current->setNext( newNode );
current

head 2 6 8 7 1 size=5

2 4 3

newNode 9 1
Linked Lists / Slide 72

Doubly-linked List
1. newNode->setNext( current->getNext() );
2. newNode->setprev( current );
3. (current->getNext())->setPrev(newNode);
4. current->setNext( newNode );
5. current = newNode;
6. size++;

head 2 6 8 7 1 size=6

2 4 3

newNode 9 1

current
Linked Lists / Slide 73

Insert a node in doubly linked list

1. Insert node at the start


2. Insert internal node
3. Insert node at the end
Linked Lists / Slide 74

Insert node at the start

new_node next=head;
head prev=new_node;
new_node prev=null;
head=new_node;

A B C
Linked Lists / Slide 75

Insert Internal node


while (p!=insert_position)
{
p=p next;
}
store_next=p next;
p next=new_node;
new_node prev=p;
new_node next=store_next;
store_next prev=new_node;
Linked Lists / Slide 76

Insert node at the end

while(p next!=null)
{
p=p next;
}
p next-new_node;
new_node prev=p;
new_node next=null;
Linked Lists / Slide 77
Linked Lists / Slide 78

Delete a node from doubly link


list
delete starting node:
p=head;
head=head next;
head prev=null;
delete(p);
Linked Lists / Slide 79

Delete the internal node


while(p!-delate_position)
{
p=p next;
}
store_next=p next;
store_prev=p prev;
store_next prev=store_prev;
store_prev next=store_next;
delete(p);
Linked Lists / Slide 80

Delete the last node

While(p next!=null)
{
p=p next;
}
store_prev=p prev;
store_prev next=null;
delete(p);
Linked Lists / Slide 81
Linked Lists / Slide 82

Reverse a Doubly linked List


if(curr ==null)// node not exist means zero node
if(curr next==null)//no need to reverse
curr = head;
while(curr !=null)
{
temp=curr prev;
curr prev=curr next;
curr next=temp;
curr=curr prev;
}
if(temp !=null)
temp=temp prev;
Linked Lists / Slide 83
Linked Lists / Slide 84

Circularly-linked lists
 The next field in the last node in a singly-linked
list is set to NULL.
 Moving along a singly-linked list has to be done
in a watchful manner.
 Doubly-linked lists have two NULL pointers:
prev in the first node and next in the last node.
 A way around this potential hazard is to link the
last node with the first node in the list to create
a circularly-linked list.
Linked Lists / Slide 85

Assignment#01
Create a Doubly linked lists and perform
following operations on list
1.Create A New Doubly Linked List
2.Display the Doubly Linked List
3.Add to an Empty Doubly Linked List
4.Add at Starting of the Doubly Linked List
5.Add at Ending
6.Add After a Node
7.Add Before a Node
8.Delete a Node
9.Reverse the Doubly Linked List

What is Complexity of Algorithms?


•What is Time Complexity?
•Calculating Time Complexity
•Types of Notations for Time Complexity
Linked Lists / Slide 86

Quiz#01

Problem Statement:

1. Write a program to insert a node at the


beginning of a linked list 5
2. Write a program to insert a node at any
nth position of the linked list 5
Linked Lists / Slide 87

 The next method in the singly-linked list or


doubly-linked list moves the current pointer to the
next node and every time it checks whether the
next pointer is NULL or not.
 Similarly the back method in the double-linked
list has to be employed carefully if the current is
pointing the first node.
 In this case, the prev pointer is pointing to NULL.
If we do not take care of this, the current will be
pointing to NULL.
 So if we try to access the NULL pointer, it will
result in an error.
 To avoid this, we can make a circularly linked list.

87 AL
Linked Lists / Slide 88

Cicularly Linked List


 Two views of a circularly linked list:
current

head 2 6 8 7 1 size=5

current
6
8
size=5
head 2

1
Linked Lists / Slide 89

Josephus Problem
 A case where circularly linked list comes in
handy is the solution of the Josephus Problem.
 Consider there are 10 persons. They would like
to choose a leader.
 The way they decide is that all 10 sit in a circle.
 They start a count with person 1 and go in
clockwise direction and skip 3. Person 4
reached is eliminated.
 The count starts with the fifth and the next
person to go is the fourth in count.
 Eventually, a single person remains.
Linked Lists / Slide 90

Josephus Problem
 N=10, M=3

4
3 5

2 6

1
7

10
8
9
Linked Lists / Slide 91

Josephus Problem
 N=10, M=3
eliminated

4
3 5

2 6

1
7

10
8
9
Linked Lists / Slide 92

Josephus Problem
 N=10, M=3
eliminated

4
3 5
8
2 6

1
7

10
9
Linked Lists / Slide 93

Josephus Problem
 N=10, M=3
eliminated

4
3 5
8
6
2

1
7

10
9
Linked Lists / Slide 94

Josephus Problem
 N=10, M=3
eliminated

4
3 5
8
6
2

1 7

10
9
Linked Lists / Slide 95

Josephus Problem
 N=10, M=3
eliminated

4
5
8
6
2

1 7

3
10
9
Linked Lists / Slide 96

Josephus Problem
 N=10, M=3
eliminated

4
5
8
6
2

1 7

10
9
Linked Lists / Slide 97

Josephus Problem
 N=10, M=3
eliminated

4
5
8
6
2

1 7

10

9
Linked Lists / Slide 98

Josephus Problem
 N=10, M=3
eliminated

4
5
8
6
2

10

1
Linked Lists / Slide 99

Josephus Problem
 N=10, M=3
eliminated

4
5
8

10

6
Linked Lists / Slide 100

Josephus Problem
#include "CList.cpp"
void main(int argc, char *argv[])
{
CList list;
int i, N=10, M=3;
for(i=1; i <= N; i++ ) list.add(i);

list.start();
while( list.length() > 1 ) {
for(i=1; i <= M; i++ ) list.next();
cout << "remove: " << list.get() << endl;
list.remove();
}
 cout << "leader is: " << list.get() << endl;
}
Linked Lists / Slide 101

Josephus Problem
 Using a circularly-linked list made the solution
trivial.
 The solution would have been more difficult if
an array had been used.
 This illustrates the fact that the choice of the
appropriate data structures can significantly
simplify an algorithm. It can make the algorithm
much faster and efficient.
Linked Lists / Slide 102

Variations of Linked Lists


 Circular linked lists
 The last node points to the first node of the list

A B C

Head

 How do we know when we have finished traversing


the list? (Tip: check if the pointer of the current
node is equal to the head.)
Linked Lists / Slide 103

Variations of Linked Lists


 Doubly linked lists
 Each node points to not only successor but the
predecessor
 There are two NULL: at the first and last nodes in the
list
 Advantage: given a node, it is easy to visit its
predecessor. Convenient to traverse lists backwards

 A B C 

Head
Linked Lists / Slide 104

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.

Das könnte Ihnen auch gefallen