0% found this document useful (0 votes)
3 views36 pages

Lecture 9

The document discusses linked lists as a data storage structure that addresses the limitations of arrays, such as slow search and insertion times. It covers various types of linked lists, including simple, double-ended, sorted, and doubly linked lists, as well as their applications in implementing abstract data types like stacks and queues. Additionally, it provides algorithms for traversing, inserting, and deleting nodes in linked lists, highlighting their versatility and efficiency in certain scenarios.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views36 pages

Lecture 9

The document discusses linked lists as a data storage structure that addresses the limitations of arrays, such as slow search and insertion times. It covers various types of linked lists, including simple, double-ended, sorted, and doubly linked lists, as well as their applications in implementing abstract data types like stacks and queues. Additionally, it provides algorithms for traversing, inserting, and deleting nodes in linked lists, highlighting their versatility and efficiency in certain scenarios.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 36

Data Structures and Algorithms

Linked Lists
Linked Lists
 In last sessions saw that arrays had
certain disadvantages as data storage
structures.
 In an unordered array, searching is slow,
 whereas in an ordered array, insertion is
slow.
 In both kinds of arrays deletion is slow.
 Also, the size of an array can't be changed
after it's created.

Linked Lists 2
Linked Lists
 In this session we'll look at a data storage structure
that solves some of these problems: the linked list.
 Linked lists are probably the second most commonly
used general-purpose storage structures after arrays.
 The linked list is a versatile mechanism suitable for
use in many kinds of general-purpose databases.
 It can also replace an array as the basis for other
storage structures such as stacks and queues. In fact,
you can use a linked list in many cases where you use
an array (unless you need frequent random access to
individual items using an index).

Linked Lists 3
Linked Lists
 Linked lists aren't the solution to all data storage
problems, but they are surprisingly versatile and
conceptually simpler than some other popular
structures such as trees.
 We'll investigate their strengths and weaknesses as
we go along.
 We'll look at
 simple linked lists,
 double-ended lists,
 sorted lists,
 doubly linked lists,
 Linked lists as a stack
 Linked lists as a Queue

Linked Lists 4
Links
 In a linked list, each data item is embedded in
a link.
 A link is an object of a class called something
like Link. Because there are many similar links
in a list, it makes sense to use a separate
class for them, distinct from the linked list
itself. Each link object contains a reference
(usually called next) to the next link in the list.
 A field in the list itself contains a reference to
the first link.

Linked Lists 5
Links
 Here's part of the definition of a class Link. It contains
some data and a reference to the next link.

class Link
{
public int iData; // data
public double dData; // data
public Link next; // reference to next link
}
 This kind of class definition is sometimes called self-
referential because it contains a field—called next in
this case—of the same type as itself.

Linked Lists 6
Traversing a Linked List
Algorithm 9.1: (Traversing a Linked List) TRAVERSE(LIST,START)
Let LIST be a linked list in memory. This algorithm
traverses LIST, applying an operation PRECESS
to each element of LIST. The variable CURRENT
points to the node currently being processed.

1. Set CURRENT:=START. [Initializes pointer CURRENT.]


2. Repeat Step 3 and 4 while CURRENT!=NULL.
3. Apply PROCESS to DATA[CURRENT].
4. Set CURRENT:= NEXT[CURRENT].
[CURRENT now points to the next node.]
[End of step 2 loop.]
5. Exit

Linked Lists 7
Inserting at the Beginning of a LIST

Algorithm 9.2: INSERTFIRST( START, ITEM)


This algorithm inserts ITEM as the first node in the LIST.

1. Set DATA[NEW] = ITEM;


[Copies new data into new node.]
2. Set NEXT[NEW] = START.
[New node now points to the original first node.]
3. Set START := NEW.
[Changes START so it points to the new node.]
4. Exit

Linked Lists 8
Deleting at the Beginning of a LIST

Algorithm 9.3: DELETEFIRST( START, ITEM)


This algorithm deletes a node ITEM from the
beginning of the LIST.
1. If START = NULL, than: [If List is already Empty.]
a) Set ITEM := NULL. [Nothing to
delete.]
b) Print “LIST EMPTY” and Return.
2. Set ITEM := DATA[FIRST]. [Save data to ITEM.]
3. Set FIRST:= NEXT[FIRST]. [Delete it.]
4. Return.

Linked Lists 9
Finding and Deleting Specified Links

 Our next example is a methods to


search a linked list for a data item with a
specified key value, and to delete an
item with a specified key value.

Linked Lists 10
Finding a Specified Links
Algorithm 9.4: FIND( START, ITEM, LOC)
Here LIST is a linked list in memory. This algorithm finds the node
LOC where ITEM first appears in LIST, or sets LOC :=NULL.

1. Set PTR := START.


2. Repeat while DATA[PTR] ≠ ITEM:
If NEXT[PTR] = NULL, then: [ If end of list.]
Set LOC := NULL, and Exit. [ Didn't find it.]
Else:
Set PTR := NEXT[PTR]. [PTR now points to the next
node.]
[End of if Structure.]
[End of Step 2 Loop.]
3. Set LOC := PTR. [If Search is successful.]
4. Exit.

Linked Lists 11
Deleting Specified Links
Algorithm 9.5 :DELETE(LIST, START, ITEM)
This algorithm deletes from a linked list the first node N
which contains the given ITEM of information.
1. Set CURR := FIRST and Set PREV := FIRST.
2. if CURR=NULL, than: [If List is empty.]
a) LOC := NULL.
b) Print "List Empty" and return.
3. Repeat while DATA[CURR] ≠ ITEM: [ Search for link.]
If NEXT[CURR] = NULL, than,
return NULL. [Didn't find it.]
Else [Go to next link.]
Set PREV := CURR and CURR := NEXT[CURR] .
[End of step 3 loop.]
4. If CURR := FIRST, than: [ If first link.]
FIRST := NEXT[FIRST]. [Change first.]
Else
NEXT[PREV] := NEXT[CURR]. [Bypass it.]
5. Return.

Linked Lists 12
Double-Ended Lists

A double-ended list is similar to an


ordinary linked list, but it has one
additional feature: a reference to the last
link as well as to the first.

Linked Lists 13
Inserting and Deleting the last and
First Element of Double-Ended List.
 The reference to the last link permits us to
insert a new link directly at the end of the list
as well as at the beginning.
 Of course, we can insert a new link at the end
of an ordinary single-ended list by iterating
through the entire list until we reach the end,
but this is inefficient.
 Access to the end of the list as well as the
beginning makes the double-ended list
suitable for certain situations that a single-
ended list can't handle efficiently. One such
situation is implementing a queue.

Linked Lists 14
Inserting at the Beginning of a Double-
Ended LIST
Algorithm 9.6: INSERTFIRST( START, LAST, ITEM)
This algorithm inserts ITEM as the first node in the LIST.

1. Set DATA[NEW] = ITEM;


[Copies new data into new node.]
2. IF START=NULL, than: [If empty list.]
Set LAST := NEW. [NewLink <-- last.]
3. Set NEXT[NEW] = START.
[New node now points to the original first node.]
4. Set START := NEW.
[Changes START so it points to the new node.]
5. Return.

Linked Lists 15
Inserting at the End of a Double-
Ended LIST

Linked Lists 16
Inserting at the End of a Double-
Ended LIST
Algorithm 9.7: INSERTLAST( START, LAST, ITEM)
This algorithm inserts ITEM as the LAST node in the LIST.

1. Set DATA[NEW] = ITEM;


[Copies new data into new node.]
2. IF START=NULL, than: [If empty list.]
Set FIRST := NEW. [first --> newLink.]
Else
Set NEXT[LAST] := NEW.
3. Set LAST := NEW.
[Changes LAST so it points to the new node.]
4. Set NEXT[NEW] := NULL.
5. Return.

Linked Lists 17
Deleting at the Beginning of a double-
ended LIST
Algorithm 9.8: DELETEFIRST( START,LAST, ITEM)
This algorithm deletes a node ITEM from the beginning of a
double-ended list LIST.

1. If START = NULL, than: [If List is already Empty.]


a) Set ITEM := NULL. [Nothing to
delete.]
b) Print “LIST EMPTY” and Return.
2. Set ITEM := DATA[FIRST]. [Save data to ITEM.]
3. IF NEXT[FIRST] = NULL. [if only one item.]
Set LAST := NULL. [null <-- last.]
4. Set FIRST:= NEXT[FIRST]. [Delete it.]
5. Return.

Linked Lists 18
Abstract Data Types
 Stacks and queues are examples of ADTs.
We've already seen that both stacks and
queues can be implemented using arrays.
 Let's see how stacks and queues can be
implemented using linked lists. This will
demonstrate the "abstract" nature of stacks
and queues: how they can be considered
separately from their implementation.

Linked Lists 19
A Stack Implemented by a Linked List

 When we created a stack in the last chapter,


we used an ordinary array to hold the stack's
data. The stack's push() and pop() operations
were actually carried out by array operations,
which insert data into, and take it out of, an
array.
 We can also use a linked list to hold a stack's
data.
 In this case the push() and pop() operations
would be carried out by calling the methods of
insertFirst() and deleteFirst() for a single-
ended linkedList.

Linked Lists 20
A Stack Implemented by a Linked
List(Java Code)
class LinkStack
{
private LinkList theList;
public LinkStack() // constructor
{ theList = new LinkList(); }
public void push(int item) // put item on top of stack
{
theList.insertFirst(item);
}
public int pop() // take item from top of stack
{ return theList.deleteFirst(); }
public boolean isEmpty() // true if stack is empty
{ return ( theList.isEmpty() ); }
public void displayStack()
{
System.out.print("Stack (top-->bottom): ");
theList.displayList();
}
} // end class LinkStack

Linked Lists 21
A Queue Implemented by a Linked List

 Here'sa similar example of an ADT


implemented with a linked list.
 Queue can be implemented as a double-
ended linked list.

Linked Lists 22
A Queue Implemented by a Linked
List (java Code)
class LinkQueue
{
private FirstLastList theList; // a double-ended list
public LinkQueue() // constructor
{ theList = new FirstLastList(); } // make a 2-ended list
public boolean isEmpty() // true if queue is empty
{ return theList.isEmpty(); }
public void insert(double j) // insert, rear of queue
{
theList.insertLast(j);
}
public double remove() // remove, front of queue
{
return theList.deleteFirst();
}
public void displayQueue()
{
System.out.print("Queue (front-->rear): ");
theList.displayList();
}
} // end class LinkQueue

Linked Lists 23
Sorted Lists
 In linked lists we've seen thus far, there was no requirement that
data be stored in order.
 However, for certain applications it's useful to maintain the data in
sorted order within the list. A list with this characteristic is called a
sorted list.
 In a sorted list, the items are arranged in sorted order by key value.
 Deletion is often limited to the smallest (or the largest) item in the
list, which is at the start of the list, although sometimes find() and
delete() methods, which search through the list for specified links,
are used as well.
 In general you can use a sorted list in most situations where you
use a sorted array.
 The advantages of a sorted list over a sorted array are speed of
insertion (because elements don't need to be moved) and the fact
that a list can expand to fill available memory, while an array is
limited to a fixed size. However, a sorted list is somewhat more
difficult to implement than a sorted array.

Linked Lists 24
Insert an Item in a Sorted List
Algorithm 9.9: INSERT( START, ITEM)
This algorithm inserts ITEM in a sorted list LIST.

1. Set DATA[NEWLINK] := ITEM [Make a new Link.]


2. Set PREVIOUS := FIRST.
3. Set CURRENT := FIRST. [Start at first. ]
[ Until end of list, or ITEM > CURRENT. ]
4. Repeat while CURRRENT ≠ NULL and ITEM > DATA[CURRENT]
a) Set PREVIOUS := CURRENT.
b) Set CURRENT := NEXT[CURRENT]. [Go to next item. ]
[End of step4 loop.]

5. If PREVIOUS=FIRST, than [If insertion at beginning of list. ]


a) Set FIRST := NEWLINK [FIRST --> NEWLINK.]
else [ not at beginning.]
a) Set NEXT[PREVIOUS] : = NEWLINK.[ old PREV --> NEWLINK.]
6. Set NEXT[NEWLINK] := CURRENT. [ NEWLINK --> OLD CURRNT.]

Linked Lists 25
List Insertion Sort
 A sorted list can be used as a fairly efficient sorting mechanism.
 Suppose you have an array of unsorted data items. If you take
the items from the array and insert them one by one into the
sorted list, they'll be placed in sorted order automatically. If you
then remove them from the list and put them back in the array,
they array will be sorted.
 It turns out this is substantially more efficient than the more usual
insertion sort within an array, described in lecture 5. This is
because fewer copies are necessary. It's still an O(N2) process,
because inserting each item into the sorted list involves
comparing a new item with an average of half the items already in
the list, and there are N items to insert, resulting in about N 2/4
comparisons.
 However, each item is only copied twice: once from the array to
the list, and once from the list to the array. N*2 copies compare
favorably with the insertion sort within an array, where there are
about N2 copies.

Linked Lists 26
Doubly Linked Lists

Linked Lists 27
Doubly Linked Lists
 Let's examine another variation on the linked
list: the doubly linked list (not to be confused
with the double-ended list).
 What's the advantage of a doubly linked list?
 A potential problem with ordinary linked lists is that
it's difficult to traverse backward along the list. A
statement like
current= current.next;
steps conveniently to the next link, but there's no
corresponding way to go to the previous link.
Depending on the application, this could pose
problems.

Linked Lists 28
Doubly Linked Lists
 For example, imagine a text editor in which a linked list is
used to store the text. Each text line on the screen is
stored as a String object embedded in a link. When the
editor's user moves the cursor downward on the screen,
the program steps to the next link to manipulate or
display the new line. But what happens if the user moves
the cursor upward? In an ordinary linked list, you'd need
to return current (or its equivalent) to the start of the list
and then step all the way down again to the new current
link. This isn't very efficient. You want to make a single
step upward. The doubly linked list provides this
capability. It allows you to traverse backward as well as
forward through the list. The secret is that each link has
two references to other links instead of one. The first is to
the next link, as in ordinary lists. The second is to the
previous link.

Linked Lists 29
Traversal of Doubly linked list from
end to start.
 Traversing in Forward direction is the same as the we
have seen in singles ended lists
 But in doubly links list we can travers the list in Backward
direction as well. The Traverse Backward algorithms is
method is similar but starts at the last element in the list
and proceeds toward the start of the list, going to each
element's previous field.
 The following steps show shows how this works:
 Set CURRENT := LAST. [ start at end.]
 Repeat while CURRENT ≠ NULL: [ until start of list.]
 Set CURRENT := PREVIOUS[CURRENT].[ move to previous link.]
 Incidentally, some people take the view that, because you can go
either way equally easily on a doubly linked list, there is no preferred
direction and therefore terms like previous and next are inappropriate.
If you prefer, you can substitute direction-neutral terms such as LEFT
and RIGHt.
Linked Lists 30
Insertion Doubly linked list

Linked Lists 31
Inserting at the Beginning of a LIST

Algorithm 9.10: INSERTFIRST( FIRST, LAST, ITEM)


This algorithm inserts ITEM as the first node in a doubly
linked list LIST.

1. Set DATA[NEWLINK] = ITEM; [create new link.]


2. if FIRST = NULL, than: [If Empty List.]
Set LAST := NEWLINK. [newLink <-- last.]
Else
Set PREVIOUS[FIRST] := NEWLINK. [NEWLINK <-- OLD
FIRST.]
[End of If Structure.]

3. Set NEXT[NEWLINK] := FIRST. [ NEWLINK --> OLD FIRST.]


4. Set FIRST = NEWLINK. [ FIRST --> NEWLINK.]
5. Exit.

Linked Lists 32
Deletion in a doubly Linked LIST

 There are three deletion routines: deleteFirst(),


deleteLast(), and deleteKey(). The first two are fairly
straightforward. In deleteKey(), the key being deleted
is current.
 Assuming the link to be deleted is neither the first nor
the last one in the list, then the next field of
PREVIOUS[CURRENT] (the link before the one being
deleted) is set to point to NEXT[CURRENT] (the link
following the one being deleted), and the PREVIOUS
field of NEXT[CURRENT] is set to point to
PREVIOUS[CURRENT]. This disconnects the current
link from the list.

Linked Lists 33
Deletion in a doubly Linked LIST

Linked Lists 34
Deleting an arbitrary link
Algorithm 9.11 : DELETE(LIST, FIRST,LAST, ITEM, LOC)
This algorithm deletes from a linked list the first node N which contains the
given ITEM of information.
1. Set CURRENT := FIRST.
2. if CURRENT=NULL, than: [If List is empty.]
a) LOC := NULL.
b) Print "List Empty" and return.
3. Repeat while DATA[CURRENT] ≠ ITEM: [ Search for link.]
If NEXT[CURRENT] = NULL, than:
Print “Item not found” return NULL. [Didn't find it.]
4. If CURRENT=FIRST, than: [ first item?.]
Set FIRST = NEXT[CURRENT] [ first --> old next.]
Else [if not first than: old previous --> old next.]
Set NEXT[PREVIOUS[CURRENT]] := NEXT[CURRENT].
5. If CURRENT=LAST, than: [ last item?]
Set LAST = PREVIOUS[CURRENT]; [ old previous <--
last.]
else [ not last than old previous <-- old next.]
Set PREVIOUS[NEXT[CURRENT]] := .PREVIOUS[CURRENT]
Linked Lists 35
The End

You might also like