data structures and algorithms lecture 7,8 and 9 (linked list) instructor: quratulain date: 25, 29...

37
Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25 , 29 September and 2 October, 2009 Faculty of Computer Science, IBA

Upload: gwendolyn-maude-ellis

Post on 28-Dec-2015

213 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

Data Structures and Algorithms

Lecture 7,8 and 9 (Linked List)

Instructor: Quratulain

Date: 25 , 29 September and 2 October, 2009

Faculty of Computer Science, IBA

Page 2: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

2

Why need Link List?

The array implementation has serious drawbacks:◦ you must know the maximum

number of items in your collection when you create it.

◦ must be in continuous manner.We can use a structure called a

linked list to overcome this limitation.

Page 3: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

3

Introduction to Link ListThe linked list is a very flexible

dynamic data structureA programmer need not worry about

how many items a program will have to accommodate

In a linked list, each item is allocated space as it is added to the list. A link is kept with each item to the next item in the list.

next

elem node

Page 4: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

4

Anatomy of a linked list

A linked list consists of:◦A sequence of nodes

a b c d

Each node contains a valueand a link (pointer or reference) to some other nodeThe last node contains a null link

The list may have a header

myList

Page 5: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

5

More terminology

A node’s successor is the next node in the sequence◦The last node has no successor

A node’s predecessor is the previous node in the sequence◦The first node has no predecessor

A list’s length is the number of elements in it◦A list may be empty (contain no

elements)

Page 6: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

6

Pointers and references In C and C++ we have “pointers,” while in Java

we have “references”These are essentially the same thingThe difference is that C and C++ allow you to

modify pointers in arbitrary ways, and to point to anything

In Java, a reference is more of a “black box,” or ADT Available operations are:

dereference (“follow”) copy compare for equality

There are constraints on what kind of thing is referenced: for example, a reference to an array of int can only refer to an array of int

Page 7: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

7

List Implementation using Linked ListsLinked list

◦Linear collection of self-referential class objects, called nodes

◦Connected by pointer links◦Accessed via a pointer to the first node of the

list◦Link pointer in the last node is set to null to

mark the list’s endUse a linked list instead of an array when

◦You have an unpredictable number of data elements

◦You want to insert and delete quickly.

Page 8: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

8

Self-Referential Class Self-referential structures

◦ Class that contains a pointer to a class of the same type◦ Can be linked together to form useful data structures

such as lists, queues, stacks and trees◦ Terminated with a NULL reference

Diagram of two self-referential class objects linked together

100

NULL pointer (points to nothing)Data member and pointer

500…

3 2

class node { int data; node next;…}

Page 9: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

9

Creating referencesThe keyword new creates a new

object, but also returns a reference to that object

For example, Person p = new Person("John")◦new Person("John") creates the

object and returns a reference to it◦We can assign this reference to p, or

use it in other ways

Page 10: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

10

Creating links in Java

class node { int value; node next; node (int v, node n) { // constructor

value = v; next = n;}

} node temp = new node(17, null); temp = new node(23, temp); temp = new node(97, temp); node myList = new node(44, temp);

44 97 23 17

myList:

Page 11: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

11

Singly-linked listsHere is a singly-linked list:

Each node contains a value and a link to its successor (the last node has no successor)

The header points to the first node in the list (or contains the null link if the list is empty)

a b c d

myList

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

Page 12: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

12

Singly-linked lists in Java public class SLinkList {

Private node start;

public SLinkList() { this.first = null;

}

// methods...

Public void Addnode(int d){ … } Public void getlistnode(){ …}

}

This class actually describes the header of a singly-linked list

However, the entire list is accessible from this header

Users can think of the SLL as being the list◦ Users shouldn’t have to

worry about the actual implementation

Page 13: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

13

Singly Linked List nodes in Java

public class node { protected Object element; protected node next;

protected node(Object elem, node next) { this.element = elem; this.next = next;

}}

Page 14: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

14

Creating a simple listTo create the list ("one", "two", "three"):SLinkList numerals = new SLinkList();Numerals.start =

new node("one", new node("two", new node("three", null)));

threetwoone

numerals

Page 15: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

15

Traversing a SLinkList

The following method traverses a list (and prints its elements):

public void printFirstToLast() { for (node curr = start; curr != null; curr = curr.next) { System.out.print(curr.element + " ");

}}

You would write this as an instance method of the SLinkList class

Page 16: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

16

Traversing a SLinkList (animation)

threetwoone

numerals

curr

Page 17: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

17

Inserting a node into a SLinkListThere are many ways you might

want to insert a new node into a list:◦As the new first element◦As the new last element◦Before a given node (specified by a

reference)◦After a given node◦Before a given value◦After a given value

All are possible, but differ in difficulty

Page 18: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

18

Inserting as a new first elementThis is probably the easiest

method to implementIn class SLinkList (not node): void insertAtFront(node n) {

n.next = this.start;this.start = n;

}

Notice that this method works correctly when inserting into a previously empty list

Page 19: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

19

Inserting a node after a given valuevoid insertAfter(Object obj, node n) {

for(node here =this.start; here != null;here = here.next) {

if (here.element.equals(obj)) {

n.next = here. next;

here. next = n;

return;

} // if

} // for

// Couldn't insert--do something reasonable!

}

Page 20: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

20

Inserting after (animation)

threetwoone

numerals

2.5n

Find the node you want to insert afterFirst, copy the link from the node that's already in the listThen, change the link in the node that's already in the list

Page 21: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

21

Deleting a node from a SLinkListIn order to delete a node from a

SLL, you have to change the link in its predecessor

This is slightly tricky, because you can’t follow a pointer backwards

Deleting the first node in a list is a special case, because the node’s predecessor is the list header

Page 22: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

22

Deleting an element from a SLL

threetwoone

numerals

threetwoone

numerals

• To delete the first element, change the link in the header

• To delete some other element, change the link in its predecessor

• Deleted nodes will eventually be garbage collected

Page 23: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

23

Deleting from a SLinkList

public void delete(node del) { node temp = del. next; // If del is first node, change link in header if (del == first) first = temp; else { // find predecessor and change its link node pred = first; while (pred.next != del) pred = pred.next; pred. next = temp;

} }

Page 24: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

24

Garbage CollectionWhat happens to objects that have no

references to them? They are inaccessible to the programJava system will remove them and recycle

the memory (usually when low on memory)How this is done is up to the

implementationI’ll describe two approaches:

◦Reference counting (has problems with cycles) ◦Mark and sweep, or tracing

Compaction is also important

Page 25: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

25

Doubly-linked lists

Here is a doubly-linked list (DLinkList):

Each node contains a value, a link to its successor (if any), and a link to its predecessor (if any)

The header points to the first node in the list and to the last node in the list (or contains null links if the list is empty)

myDLinkList

a b c

Page 26: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

26

DLinkLists compared to SLinkLists

Advantages:◦ Can be traversed in

either direction (may be essential for some programs)

◦ Some operations, such as deletion and inserting before a node, become easier

Disadvantages:◦ Requires more space◦ List manipulations are

slower (because more links must be changed)

◦ Greater chance of having bugs (because more links must be manipulated)

Page 27: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

27

Constructing SLinkLists and DLinkLists

public class SLinkList {

private node first;

public SLinkList () { this.first = null;

}

// methods... }

public class DLinkList {

private node first; private node last;

public DLinkList () { this.first = null; this.last = null;

}

// methods... }

Page 28: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

28

DLinkList nodes in Java

public class node { protected Object element; protected node pred, succ;

protected node(Object elem, node pred, node succ) { this.element = elem; this.pred = pred; this.succ = succ;

}}

Page 29: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

29

Deleting a node from a DLinkList

Node deletion from a DLinkList involves changing two links

Deletion of the first node or the last node is a special case

Garbage collection will take care of deleted nodes

myDLinkList

a b c

Page 30: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

30

Other operations on linked listsMost “algorithms” on linked lists

—such as insertion, deletion, and searching—are pretty obvious; you just need to be careful

Sorting a linked list is just messy, since you can’t directly access the nth element—you have to count your way through a lot of other elements

Page 31: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

31

Analyzing the Singly Linked List

Method Time

Inserting at the head

Inserting at the tail

Deleting at the head

Deleting at the tail

O(1)

O(1)

O(1)

O(n)

Page 32: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

32

Types of linked lists

Types of linked lists:◦ Singly linked list Begins with a pointer to the first node Terminates with a null pointer Only traversed in one direction

◦ Circular, singly linked Pointer in the last node points

back to the first node◦ Doubly linked list Two “start pointers” – first element and last element Each node has a forward pointer and a backward pointer Allows traversals both forwards and backwards

◦ Circular, doubly linked list Forward pointer of the last node points to the first node

and backward pointer of the first node points to the last node

Page 33: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

33

Circular Link ListA Circular Linked List is a special type of Linked

List It supports traversing from the end of the list to

the beginning by making the last node point back to the head of the list

A Rear pointer is often used instead of a Head pointer

Rear

10 20 40 7055

Page 34: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

34

Circular linked listsCircular linked lists are usually

sortedCircular linked lists are useful for

playing video and sound files in “looping” mode

They are also a stepping stone to implementing graphs.

Page 35: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

35

Issues with circular listHow do you know when you’re

done?◦Make sure you save the head

reference.◦When (cur.next == head) you’ve

reached the endHow are insertion and deletion

handled?◦No special cases!◦Predecessor to head node is the last

node in the list.

Page 36: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

36

The Josephus Problem(One of many variations…)

The founder of a startup is forced to lay off all but one employee. Not having any better way to decide, he arranges all employees in a circle and has them count off. The 10th employee in the circle is laid off, and the count begins again. The last person is not laid off.

If there are N employees, where should you sit to avoid being laid off?

Page 37: Data Structures and Algorithms Lecture 7,8 and 9 (Linked List) Instructor: Quratulain Date: 25, 29 September and 2 October, 2009 Faculty of Computer Science,

CSE 246 Data Structures and Algorithms Fall2009 Quratulain

37

SolutionModel the circle of employees as

a circular linked listImplement the counting off

process, and delete the 10th employee each time

After N-1 people are deleted, there should be only one employee left.

That employee’s original position number is the solution to the problem.