Top Banner
1 Linked Lists Gordon College Prof. Brinton
58

1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

Dec 16, 2015

Download

Documents

Mireya Housley
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

1

Linked Lists

Gordon College

Prof. Brinton

Page 2: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

2

Linked List Basics

• Why use?1. Efficient insertion or deletion into middle of list.

(Arrays are not efficient at doing this.)

2. Dynamic creation

• Any drawbacks?Yes, linked lists take up extra space - remember

the pointers.

Page 3: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

3

The Linked List Node• Contains 2 items:

– Payload for linked list entries– Pointer(s) to surrounding links

class Node {

public: Node(int p) {next=NULL; item=p; };

int item; Node* next;

};

Note: the node class can either be private within the Linked list class or it can stand on its own.

Page 4: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

4

Linked List Classclass LinkedList{ public: LinkedList() { first=NULL; mySize=0; }; const int size() {return mySize; }; void insert(int p, int pos ); void display(ostream & out); void erase(int value); private: class Node

{ public:

Node(int p) {next=NULL; item=p; };int item; Node* next;

};

int mySize;Node * first;};

Page 5: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

5

Inserting a new node

Steps:1. Find location within list

2. Create new node with payload and pointer to current node’s next

3. Assign address of new node to current node’s next

Note: order is essential

Page 6: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

6

Inserting a new node

• Exception cases: begin and end of list

Begin Case:1. Create new node

2. Assign address found in first to current node’s next

3. Place address of new node in first

End case:1. Create new node

2. Put NULL in new node’s next

3. Assign address of new node to next of last node

Page 7: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

7

Deleting a node

Steps

1. Find the node to delete (keep finger on previous node)

2. Assign next address in previous node to next address of node to delete

3. Delete current node

Page 8: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

8

Deleting a node

Exception cases: begin and end of list

Begin:

1. Assign address of current next to first

2. Delete current node

End:

1. Place NULL in previous node’s next

2. Delete current node

Page 9: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

9

Order of Magnitude

How many operations does it take?1. Inserting at front of list - O(1)2. Deleting at front of list - O(1)3. Inserting at the back of list - O(n)4. Deleting at the back of list - O(n)

What happens if we add a pointer called Back that points to the last node?

Inserting at the back of the list is now O(1)How about deleting at the back?

Page 10: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

10

Order of Magnitude

• The list is still a Singly Linked List. In order to delete at the end of a list, we still must have a pointer to the predecessor to back.

Therefore O(n):1. Walk to the end of the list (keep finger on

previous node)2. Assign next address in previous node to NULL3. Delete current node

Page 11: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

11

Singly LL with back pointer

• Problems:– Insert on an empty list - must update both

pointers– Erase on one node - must update both pointers

Page 12: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

12

Doubly Linked Lists

• New Node structure:class Node {

public: Node(int p) { next=NULL; prev=NULL; item=p; };

int item;Node* prev; Node* next;

};

Page 13: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

13

Doubly Linked Lists

Inserting a node at a position

1. Find place to insert: current node

2. Set new node’s prev pointer to current node’s prev pointer

3. Set new node’s next pointer to current node

4. Set previous node’s next to new pointer

5. Set current node’s previous to new node

Page 14: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

14

Doubly Linked Lists

Removing a node at a position

1. Find node to remove: current node

2. Set previous node’s next to current’s next

3. Set next node’s (successor) prev to current node’s prev

4. Delete current

Page 15: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

15

Doubly Linked Lists

Exceptions: first and last node.

Order of Magnitude:

O(1) insert and remove at either end.

Note: also search time can be quicker if you know which end to begin searching.

Page 16: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

16

What’s a Head Node?

• Consider simple linked lists– First node is different from others– Only node that is directly accessible– Has no predecessor

• Thus insertions and deletions must consider two cases– First node or not first node– The algorithm is different for each

Page 17: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

17

Linked Lists with Head Nodes

• Dual algorithms can be reduced to one– Create a "dummy" head node– Serves as predecessor holding actual first

element

• Thus even an empty list has a head node

Page 18: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

18

Linked Lists with Head Nodes

• For insertion at beginning of list– Head node is predecessor for new node

newptr->next = predptr->next;predptr->next = newptr;

Page 19: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

19

Linked Lists with Head Nodes

• For deleting first element from a list with a head node– Head node is the predecessor

predptr->next = ptr->next;delete ptr;

Page 20: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

20

Circular Linked Lists• Set the link in last node to point to first node

– Each node now has both predecessor and successor

– Insertions, deletions now easier

• Special consideration required for insertion to empty list, deletion from single item list

Page 21: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

21

Circular Linked Lists

• Traversal algorithm must be adjusted:

if (first != NULL) // list not empty{ ptr = first;

do { // process ptr->data

ptr = ptr->next; } while (ptr != first); }

• How must this be different?

Page 22: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

22

CircularLinked ListsTraversal

if (first!=NULL){ ptr = first; //process ptr->data ptr = ptr->next; while (ptr != first) {

//process ptr->data ptr = ptr->next;

}}

if (first!=NULL){ ptr = first; do {

//process ptr->data ptr = ptr->next;

} while (ptr != first);}

Page 23: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

23

CircularLinked ListsTraversalwith Head Node

ptr = first->next;

while (ptr != first)

{

//process ptr->data

ptr = ptr->next;

}

Page 24: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

24

Polynomial Representationx2 - 4x + 7

• Consider a polynomial of degree n– Can be represented by an array

• For a sparse polynomial this is not efficient

5

Page 25: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

25

Polynomial Representationx2 - 4x + 7

• We could represent a polynomial by a list of ordered pairs– { (coef, exponent) … }

• Fixed capacity ofarray still problematic– Wasted space for

sparse polynomial

Page 26: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

26

Linked Implementation of Sparse Polynomials

• Linked list of these ordered pairs provides an appropriate solution– Each node has form shown

• Now whether sparse or well populated, the polynomial is represented efficiently (with head

nodes)

Page 27: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

27

Linked Implementation of Sparse Polynomials

How would this class look?

Page 28: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

28

Linked Implementation of Sparse Polynomialsclass Polynomial{ public: Polynomial() { first=NULL; mySize=0; }; const int size() {return mySize; }; void insert(int p, int pos ); void display(ostream & out); void erase(int value); private:

class Term {

public:int coef;unsigned expo; };

class Node { public:

Node(int co, int ex) {next=NULL; data.coef=co; data.expo = ex; };Term Data; Node* next;

};

…};

Page 29: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

29

Addition Operator

• Requires temporary pointers for each polynomial (the addends and the resulting sum)

Page 30: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

30

Addition Operator• As traversal takes place

– Compare exponents– If different, node with smaller exponent and its coefficient

attached to result polynomial– If exponents same, coefficients added, new

corresponding node attached to result polynomial

Page 31: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

31

Doubly-Linked Lists

• Bidirectional lists– Nodes have data part,

forward and backward link

• Facilitates both forward and backward traversal– Requires pointers to both first and last nodes

Page 32: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

32

Doubly-Linked Lists

• To insert a new node– Set forward and backward links to point to

predecessor and successor

Page 33: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

33

Doubly-Linked Lists

• To insert a new node– Set forward and backward links to point to

predecessor and successor

– Then reset forward link of predecessor, backward link of successor

Page 34: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

34

Doubly-Linked Lists

• To delete a node– Reset forward link of predecessor, backward link

of successor– Then delete removed node

Page 35: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

35

The STL list<T> Class Template

• A sequential container – Optimized for insertion and erasure at arbitrary

points in the sequence.– Implemented as a circular doubly-linked list with

head node.

Page 36: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

36

Comparing List<t> With Other Containers

• Note : list<T> does not support direct access – does not have the subscript operator [ ].

Property Array vector<T> deque<T> list<T>

Direct/random access ([]) (exclnt)(good)X

Sequential access

Insert/delete at front (poor)

Insert/delete in middle

Insert/delete at end

Overhead lowest low low/mediumhigh

Page 37: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

37

list<t> Iterators• list<T>'s iterator is "weaker" than that for vector<T>. vector<T>: random access iterators

list<T>: bidirectional iterators

• Operations in common ++ Move iterator to next element

(like ptr = ptr-> next) -- Move iterator to preceding element

(like ptr = ptr-> prev) * dereferencing operator

(like ptr-> data)

Page 38: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

38

list<t> Iterators• Operators in common

= assignment (for same type iterators) it1 = it2 makes it1 positioned at

same element as it2 == and !=

(for same type iterators) checks whether iterators are

positioned at the same element

Page 39: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

39

Example: Internet Addresses

• Consider a program that stores IP addresses of users who make a connection with a certain computer– We store the connections in an AddressCounter object

– Tracks unique IP addresses and how many times that IP connected

Page 40: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

40

The STL list<T> Class Template

Node structure

struct list_node

{ pointer next, prev;T data; }

Page 41: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

41

The STL list<T> Class Template

• But it's allocation/deallocation scheme is complex– Does not simply use new and delete

operations.

• Using the heap manager is inefficient for large numbers of allocation/deallocations– Thus it does it's own memory management.

Page 42: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

42

The STL list<T> Memory Management

When a node is allocated

1. If there is a node on the free list, allocate it.• This is maintained as a linked stack

2. If the free list is empty:a) Call the heap manager to allocate a block of

memory (a "buffer", typically 4K)

b) Carve it up into pieces of size required for a node of a list<T>.

Page 43: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

43

The STL list<T> Memory Management

• When a node is deallocated– Push it onto the free list.

• When all lists of this type T have been destroyed– Return it to the heap

Page 44: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

44

Case Study: Large-Integer Arithmetic

• Recall that numeric representation of numbers in computer memory places limits on their size– 32 bit integers, two's complement max

2147483647

• We will design a BigInt class– Process integers of any size– For simplicity, nonnegative integers only

Page 45: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

45

BigInt Design

• First step : select a storage structure– We choose a linked list– Each node sores a block of up to 3 consecutive

digits

– Doubly linked list for traversing in both directions

Page 46: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

46

BigInt Design

• Input in blocks of 3 integers, separated by spaces– As each new block entered, node added at end

• Output is traversal, left to right

Page 47: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

47

BigInt Design

• Addition adds the groupings right to left– Keeping track of carry digits

Page 48: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

48

Multiply-Ordered Lists

• Ordered linked list– Nodes arranged so data items are in

ascending/descending order

• Straightforward when based on one data field– However, sometimes necessary to maintain links

with a different ordering

• Possible solution– Separate ordered linked lists – but wastes space

Page 49: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

49

Multiply-Ordered Lists

• Better approach– Single list– Multiple links

Page 50: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

50

Sparse Matrices• Usual storage is 2D array or 2D vector

• If only a few nonzero entries– Can waste space

• Stored more efficiently with linked structure– Similar to sparse polynomials– Each row is a linked list– Store only nonzero entries for the row

Page 51: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

51

• For

we represent with

Sparse Matrices

A =

Page 52: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

52

Sparse Matrices

• This still may waste space– Consider if many rows were all zeros

• Alternative implementation– Single linked list– Each node has row, column,

entry, link

• Resulting list

Page 53: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

53

Sparse Matrices

• However … this loses direct access to rows

• Could replace array of pointers with– Linked list of row head nodes– Each contains pointer to non empty row list

Page 54: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

54

Sparse Matrices

• If columnwise processing is desired– Use orthogonal list– Each node stores row, column, value, pointer to

row successor, pointer to column successor

Page 55: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

55

Sparse Matrices• Note the resulting

representation of the matrix

A =

Page 56: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

56

Generalized Lists

• Examples so far have had atomic elements– The nodes are not themselves lists

• Consider a linked list of strings– The strings themselves can be linked lists of

charactersThis is an

example of a generalized list

This is an example of a

generalized list

Page 57: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

57

Generalized Lists

• Commonly represented as linked lists where– Nodes have a tag field along with data and link

• Tag used to indicate whether data field holds– Atom– Pointer

to a list

Page 58: 1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.

58

Generalized Lists

• Lists can be shared– To represent

(2, (4,6), (4,6))

• For polynomials in two variablesP(x,y) = 3 + 7x + 14y2 + 25y7 – 7x2y7 + 18x6y7