CHAPTER 4 Linked List - sharecourse.net filelinked list 2 . NCUE CSIE Wireless Communications and...

Post on 18-Mar-2019

225 views 0 download

Transcript of CHAPTER 4 Linked List - sharecourse.net filelinked list 2 . NCUE CSIE Wireless Communications and...

NCUE CSIE Wireless Communications and Networking Laboratory

CHAPTER 4

Linked List

1

NCUE CSIE Wireless Communications and Networking Laboratory

Introduction

Array

successive items locate a fixed distance

disadvantage

data movements during insertion and deletion

waste space in storing n ordered lists of

varying size

possible solution

linked list

2

NCUE CSIE Wireless Communications and Networking Laboratory

Pointer Can Be Dangerous

3

pointer

int i, *pi;

pi = &i;

pi= malloc(size of(int));

/* assign to pi a pointer to int */

pf=(float *) pi;

/* casts an int pointer to a float pointer */

NCUE CSIE Wireless Communications and Networking Laboratory

Dynamically Allocated

4

int i, *pi;

float f, *pf;

pi = (int *) malloc(sizeof(int));

pf = (float *) malloc (sizeof(float));

*pi =1024;

*pf =3.14;

printf(”an integer = %d, a float = %f\n”, *pi, *pf);

free(pi);

free(pf);

request memory

return memory

NCUE CSIE Wireless Communications and Networking Laboratory

Singly Linked Lists

5

Bat Cat Sat Vat null

First

Data Area Link Area Node:

NCUE CSIE Wireless Communications and Networking Laboratory

Insertion

6

Bat Cat Sat Vat null

First

Mat

NCUE CSIE Wireless Communications and Networking Laboratory

Delete mat from list

Deletion

7

Bat Cat Sat Vat null

First

Mat

NCUE CSIE Wireless Communications and Networking Laboratory

Create a linked list of words

Declaration

typedef struct list_node, *list_pointer;

typedef struct list_node {

char data [4];

list_pointer link;

};

Creation

list_pointer ptr =NULL;

Testing

#define IS_EMPTY(ptr) (!(ptr))

Allocation

ptr=(list_pointer) malloc (sizeof(list_node));

8

NCUE CSIE Wireless Communications and Networking Laboratory

address of

first node ptr data ptr link

e -> name (*e).name

strcpy(ptr -> data, “bat”);

ptr -> link = NULL;

9

b a t \0 null

NCUE CSIE Wireless Communications and Networking Laboratory

Create a two-node list

typedef struct list_node *list_pointer;

typedef struct list_node {

int data;

list_pointer link;

};

list_pointer ptr =NULL

10

10 20 null

ptr

NCUE CSIE Wireless Communications and Networking Laboratory

list_pointer create2( )

{

/* create a linked list with two nodes */

list_pointer first, second;

first = (list_pointer) malloc(sizeof(list_node));

second = ( list_pointer) malloc(sizeof(list_node));

second -> link = NULL;

second -> data = 20;

first -> data = 10;

first ->link = second;

return first;

}

Create a two-node list

11

10 20 null

ptr

NCUE CSIE Wireless Communications and Networking Laboratory

List Insertion

void insert(list_pointer *ptr, list_pointer node)

{

/* insert a new node with data = 50 into the list ptr after node */

list_pointer temp;

temp = (list_pointer) malloc(sizeof(list_node));

if (IS_FULL(temp)){

fprintf(stderr, “The memory is full\n”);

exit (1);

}

12

NCUE CSIE Wireless Communications and Networking Laboratory

temp->data = 50;

if (*ptr) { non-empty list

temp->link =node ->link;

node->link = temp;

}

else { empty list

temp->link = NULL;

*ptr =temp;

}

}

13

NCUE CSIE Wireless Communications and Networking Laboratory

(a) before deletion (b)after deletion

Delete node other than the first node.

List Deletion

Delete the first node.

14

10 50 20 null

ptr node

10 50 20 null

ptr node

50 20 null

ptr

10 20 null

ptr

NCUE CSIE Wireless Communications and Networking Laboratory

void delete(list_pointer *ptr, list_pointer trail,

list_pointer node)

{

/* delete node from the list, trail is the preceding node

ptr is the head of the list */

if (trail)

trail->link = node->link;

else

*ptr = (*ptr) ->link;

free(node);

}

Deletion from a list

15

NCUE CSIE Wireless Communications and Networking Laboratory

Print out a list

void print_list(list_pointer ptr)

{

printf(“The list contains: “);

for ( ; ptr; ptr = ptr->link)

printf(“%4d”, ptr->data);

printf(“\n”);

}

16

NCUE CSIE Wireless Communications and Networking Laboratory

Dynamically Linked stacks and

queues

17

null

top element link

(a) Linked stack

null

front element link

(b) Linked queue

rear

NCUE CSIE Wireless Communications and Networking Laboratory

Stacks

#define MAX_STACKS 10 /* maximum number of stacks */

typedef struct {

int key;

/* other fields */

} element;

typedef struct stack *stack_pointer;

typedef struct stack {

element item;

stack_pointer link;

};

stack_pointer top[MAX_STACKS];

18

NCUE CSIE Wireless Communications and Networking Laboratory

Queues

#define MAX_QUEUES 10 /* maximum number of queues */

typedef struct queue *queue_pointer;

typedef struct queue {

element item;

queue_pointer link;

};

queue_pointer front[MAX_QUEUE], rear[MAX_QUEUES];

19

NCUE CSIE Wireless Communications and Networking Laboratory

Push

void add(stack_pointer *top, element item)

{

/* add an element to the top of the stack */

stack_pointer temp =

(stack_pointer) malloc (sizeof (stack));

if (IS_FULL(temp)) {

fprintf(stderr, “ The memory is full\n”);

exit(1);

}

temp->item = item;

temp->link = *top;

*top= temp;

} 20

NCUE CSIE Wireless Communications and Networking Laboratory

Pop

element delete(stack_pointer *top) {

/* delete an element from the stack */

stack_pointer temp = *top;

element item;

if (IS_EMPTY(temp)) {

fprintf(stderr, “The stack is empty\n”);

exit(1);

}

item = temp->item;

*top = temp->link;

free(temp);

return item;

} 21

NCUE CSIE Wireless Communications and Networking Laboratory

Add

22

void addq(queue_pointer *front, queue_pointer *rear, element item)

{

/* add an element to the rear of the queue */

queue_pointer temp =

(queue_pointer) malloc(sizeof (queue));

if (IS_FULL(temp)) {

fprintf(stderr, “ The memory is full\n”);

exit(1);

}

temp->item = item;

temp->link = NULL;

if (*front) *rear -> link = temp;

else *front = temp;

*rear = temp;

}

NCUE CSIE Wireless Communications and Networking Laboratory

Delete

23

element deleteq(queue_pointer *front) {

/* delete an element from the queue */

queue_pointer temp = *front;

element item;

if (IS_EMPTY(*front)) {

fprintf(stderr, “The queue is empty\n”);

exit(1);

}

item = temp->item;

*front = temp->link;

free(temp);

return item;

}

NCUE CSIE Wireless Communications and Networking Laboratory

Polynomials

typedef struct poly_node *poly_pointer; typedef struct poly_node { int coef; int expon; poly_pointer link; }; poly_pointer a, b, d;

A x a x a x a xm

e

m

e em m( ) ...

1 2 0

1 2 0

coef expon link

24

NCUE CSIE Wireless Communications and Networking Laboratory

Examples

25

123 814 xxa

61014 1038 xxxb

3 14 2 8 1 0 null

8 14 -3 10 10 6 null

NCUE CSIE Wireless Communications and Networking Laboratory

Add

26

3 14

8 14

11 14

2 8 1 0

-3 10 10 6

a

b

d

(a -> expon) == (b -> expon)

NCUE CSIE Wireless Communications and Networking Laboratory

Add

27

3 14

8 14

11 14

2 8 1 0

-3 10 10 6

a

b

d

(a -> expon) < (b -> expon)

-3 10

NCUE CSIE Wireless Communications and Networking Laboratory

Add

28

3 14

8 14

11 14

2 8 1 0

-3 10 10 6

a

b

d

(a -> expon) > (b -> expon)

-3 10 2 8

NCUE CSIE Wireless Communications and Networking Laboratory

Algorithm(Add)

29

poly_pointer padd(poly_pointer a, poly_pointer b) { /* return a polynomial which is the sum of a and b */ poly_pointer front, rear, temp; int sum; rear =(poly_pointer)malloc(sizeof(poly_node)); if (IS_FULL(rear)) { fprintf(stderr, “The memory is full\n”); exit(1); } front = rear; while (a && b) switch (COMPARE(a->expon, b->expon)) {

NCUE CSIE Wireless Communications and Networking Laboratory

case -1: /* a->expon < b->expon */ attach(b->coef, b->expon, &rear); b= b->link; break; case 0: /* a->expon == b->expon */ sum = a->coef + b->coef; if (sum) attach(sum,a->expon,&rear); a = a->link; b = b->link; break; case 1: /* a->expon > b->expon */ attach(a->coef, a->expon, &rear); a = a->link; } /* copy rest of list a and then list b */ for (; a; a = a->link) attach(a->coef, a->expon, &rear); for (; b; b=b->link) attach(b->coef, b->expon, &rear); rear->link = NULL; /* delete extra initial node */ temp = front; front = front->link; free(temp); return front; } 30

NCUE CSIE Wireless Communications and Networking Laboratory

Attach a Term

31

void attach(float coefficient, int exponent, poly_pointer *ptr)

{

/* create a new node attaching to the node pointed to

by ptr. ptr is updated to point to this new node. */

poly_pointer temp;

temp = (poly_pointer) malloc(sizeof(poly_node));

if (IS_FULL(temp)) {

fprintf(stderr, “The memory is full\n”);

exit(1);

}

temp->coef = coefficient;

temp->expon = exponent;

(*ptr)->link = temp;

*ptr = temp;

}

NCUE CSIE Wireless Communications and Networking Laboratory

Analysis

32

(1)coefficient additions

0 additions min(m, n)

where m (n) denotes the number of terms in a (b).

(2)exponent comparisons

extreme case

em-1 > fm-1 > em-2 > fm-2 > … > e0 > f0

m+n-1 comparisons

(3)creation of new nodes

extreme case

m + n new nodes

summary: O(m+n)

NCUE CSIE Wireless Communications and Networking Laboratory

Erasing Polynomials

33

void earse(poly_pointer *ptr)

{

/* erase the polynomial pointed to by ptr */

poly_pointer temp;

while (*ptr) {

temp = *ptr;

*ptr = (*ptr)->link;

free(temp);

}

}

O(n)

NCUE CSIE Wireless Communications and Networking Laboratory

Circularly Linked Lists

34

circular list vs. chain

3 14 2 8 1 0 ptr

ptr

avail

temp

avail

NCUE CSIE Wireless Communications and Networking Laboratory

Maintain an Available List

35

poly_pointer get_node(void) {

/* provide a node for use */

poly_pointer node;

if (avail) {

node = avail;

avail = avail->link:

}

else {

node = (poly_pointer)malloc(sizeof(poly_node));

if (IS_FULL(node)) {

fprintf(stderr, “The memory is full\n”);

exit(1);

}

}

return node;

}

NCUE CSIE Wireless Communications and Networking Laboratory

void ret_node(poly_pointer ptr) { /* return a node to the available list */ ptr->link = avail; avail = ptr; } void cerase(poly_pointer *ptr) { /* earse the circular list ptr */ poly_pointer temp; if (*ptr) { temp = (*ptr)->link; (*ptr)->link = avail; avail = temp; *ptr = NULL; } }

(1) (2)

Independent of # of nodes in a list O(1) constant time 36

Circularly Linked Lists (Erase)

NCUE CSIE Wireless Communications and Networking Laboratory

37

null

(1) (2)

avail

ptr

avail

temp

Circularly Linked Lists (Erase)

NCUE CSIE Wireless Communications and Networking Laboratory

Head Node

Represent polynomial as circular list.

(1) zero

(2) others

38

123 814 xxa

-1 2 8 1 0 a

3 14

-1 a

Zero polynomial

NCUE CSIE Wireless Communications and Networking Laboratory

Algorithm cpadd

poly_pointer cpadd(poly_pointer a, poly_pointer b) { /* polynomials a and b are singly linked circular lists with a head node. Return a polynomial which is the sun of a and b */ poly_pointer starta, d, lastd; int sum, done = FALSE; starta = a; /* record start of a */ a = a->link; /* skip head node for a and b */ b = b->link; d = get_node(); /* get a head node for sum */ d->expon = -1; lastd = d; do { switch (COMPARE(a->expon, b->expon)) { case -1: attach(b->coef, b->expon, &lastd); b = b->link; break;

Set expon field of head node to -1

39

NCUE CSIE Wireless Communications and Networking Laboratory

case 0: if (starta == a) done = TRUE; else { sum = a->coef + b->coef; if (sum) attach(sum,a->expon,&lastd); a = a->link; b = b->link; } break; case 1: attach(a->coef,a->expon,&lastd); a = a->link; } } while (!done); lastd->link = d; return d; }

Link last node to first

40

NCUE CSIE Wireless Communications and Networking Laboratory

Additional List Operations

typedef struct list_node *list_pointer;

typedef struct list_node {

char data;

list_pointer link;

};

41

NCUE CSIE Wireless Communications and Networking Laboratory

Invert Single Linked Lists

list_pointer invert(list_pointer lead) { list_pointer middle, trail; middle = NULL; while (lead) { trail = middle; middle = lead; lead = lead->link; middle->link = trail; } return middle; }

Use two extra pointers: middle and trail.

42

NCUE CSIE Wireless Communications and Networking Laboratory

Concatenate Two Lists

list_pointer concatenate(list_pointerptr1, list_pointer ptr2) { list_pointer temp; if (IS_EMPTY(ptr1)) return ptr2; else { if (!IS_EMPTY(ptr2)) { for (temp=ptr1;temp->link;temp=temp->link); temp->link = ptr2; } return ptr1; } }

O(m) where m is # of elements in the first list

43

NCUE CSIE Wireless Communications and Networking Laboratory

Length of Circular Linked List

int length(list_pointer ptr) { list_pointer temp; int count = 0; if (ptr) { temp = ptr; do { count++; temp = temp->link; } while (temp!=ptr); } return count; }

44

NCUE CSIE Wireless Communications and Networking Laboratory

Equivalence Relations

45

A relation over a set, S, is said to be an equivalence

relation over S iff it is symmertric, reflexive, and

transitive over S.

reflexive, x=x

symmetric, if x=y, then y=x

transitive, if x=y and y=z, then x=z

NCUE CSIE Wireless Communications and Networking Laboratory

Examples

0 ≡ 4, 3 ≡ 1, 6 ≡ 10, 8 ≡ 9, 7 ≡ 4,

6 ≡ 8, 3 ≡ 5, 2 ≡ 11, 11 ≡ 0

three equivalent classes:

{0,2,4,7,11}; {1,3,5}; {6,8,9,10}

46

NCUE CSIE Wireless Communications and Networking Laboratory

A Rough Algorithm to

Find Equivalence Classes

void equivalence() { initialize; while (there are more pairs) { read the next pair <i , j>; process this pair; } initialize the output; do output a new equivalence class; while (not done); }

What kinds of data structures are adopted?

47

NCUE CSIE Wireless Communications and Networking Laboratory

First Refinement

{ initialize seq to NULL and out to TRUE while (there are more pairs) { read the next pair, < i , j>; put j on the seq[i] list; put i on the seq[j] list; } for (i=0; i<n; i++) if (out[i]) { out[i]= FALSE; output this equivalence class; } }

direct equivalence

Compute indirect equivalence

using transitivity

48

NCUE CSIE Wireless Communications and Networking Laboratory

Lists after pairs are input

typedef struct node *node_pointer ;

typedef struct node {

int data;

node_pointer link;

};

0 4 3 1 6 10 8 9 7 4 6 8 3 5 2 11 11 0

49

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [1

0]

[1

1]

11 3 11 5 7 8 6 0 4 6 3 8

4 1 0 1

0 9 2

NULL NULL NULL NULL NULL NULL

NULL NULL NULL NULL NULL NULL

Seq

NCUE CSIE Wireless Communications and Networking Laboratory

Final Version for

Finding Equivalence Classes

void main(void) { short int out[MAX_SIZE]; node_pointer seq[MAX_SIZE]; node_pointer x, y, top; int i, j, n; printf(“Enter the size (<= %d) ”, MAX_SIZE); scanf(“%d”, &n); for (i=0; i<n; i++) { /* initialize seq and out */ out[i]= TRUE; seq[i]= NULL; }

50

NCUE CSIE Wireless Communications and Networking Laboratory

/* Phase 1: Input the equivalence pairs */ printf(“Enter a pair of numbers (-1 -1 to quit): “); scanf(“%d%d”, &i, &j);

while (i>=0) {

x = (node_pointer) malloc(sizeof(node));

if (IS_FULL(x)) {

fprintf(stderr, “The memory is full\n”);

exit(1);

}

x->data= j; x->link= seq[i]; seq[i]= x;

x=(node_pointer) malloc(sizeof(node));

if (IS_FULL(x)) {

fprintf(stderr, “memory is full\n”);

exit(1);

}

x->data= i; x->link= seq[j]; seq[j]= x;

printf(“Enter a pair of numbers (-1 -1 to quit): “); scanf(“%d%d”, &i, &j); }

Insert x to the top of lists seq[i]

Insert x to the top of lists seq[ j]

Phase 1: input the equivalence

pairs

51

NCUE CSIE Wireless Communications and Networking Laboratory

/* Phase 2:output the equivalence classes */ for (i=0; i<n; i++) if (out[i]) { printf(“\nNew class: %5d”, i); out[i]= FALSE; /* set class to false */ x = seq[i]; top = NULL; /* initialize stack */ for (;;) { /* find rest of class */ while (x) { /* process list */ j = x->data; if (out[j]) { printf (“%5d”, j); out[j] = FALSE; y = x->link; x->link = top; top = x; x = y; } else x = x->link; } if (!top) break; x = seq[top->data]; top = top->link; /* unstack */ } } }

Phase 2: output the equivalence

classes

push

pop

52

NCUE CSIE Wireless Communications and Networking Laboratory

15000

0040

00012

01100

Sparse Matrices

inadequates of sequential schemes

(1) # of nonzero terms will vary after some matrix computation

(2) matrix just represents intermediate results

new scheme

Each column (row): a circular linked list with a head node

53

NCUE CSIE Wireless Communications and Networking Laboratory

Head node

Entry node

Set up for aij

# of head nodes = max{# of rows, # of columns}

Revisit Sparse Matrices

down head right

next

down entry row col right

value

entry i j

aij

54

aij

NCUE CSIE Wireless Communications and Networking Laboratory

Linked Representation

for Matrix

55

NCUE CSIE Wireless Communications and Networking Laboratory

Doubly Linked Lists

Move in forward and backward direction.

Singly linked list (in one direction only)

How to get the preceding node during deletion or insertion?

Using 2 pointers

Node in doubly linked list

left link field ( )

data field ( )

right link field ( )

56

llinkitem

rlink

NCUE CSIE Wireless Communications and Networking Laboratory

Doubly Linked Lists

typedef struct node *node_pointer;

typedef struct node {

node_pointer llink;

element item;

node_pointer rlink;

};

ptr

= ptr->rlink->llink

= ptr->llink->rlink

57

NCUE CSIE Wireless Communications and Networking Laboratory

Empty doubly linked circular list with head node

58

NCUE CSIE Wireless Communications and Networking Laboratory

Insertion into an empty

doubly linked circular list

59

NCUE CSIE Wireless Communications and Networking Laboratory

Insert

void dinsert(node_pointer node, node_pointer newnode) { /* insert newnode to the right of node */ (1) newnode->llink = node; (2) newnode->rlink = node->rlink; (3) node->rlink->llink = newnode; (4) node->rlink = newnode; }

60

NCUE CSIE Wireless Communications and Networking Laboratory

Delete

void ddelete(node_pointer node, node_pointer deleted) { /* delete from the doubly linked list */ if (node==deleted) printf(“Deletion of head node not permitted.\n”); else { (1) deleted->llink->rlink= deleted->rlink; (2) deleted->rlink->llink= deleted->llink; free(deleted); } }

61

NCUE CSIE Wireless Communications and Networking Laboratory

Which code segment below implements the insert operation

correctly for singly linked lists?

(A) void insert (Listitem pre.Listitem new) {

Linstitem next = pre, next;

new. next = null;

prt. next = new;

}

62

Question:

NCUE CSIE Wireless Communications and Networking Laboratory

(B) void insert (Listitem pre.Listitem new) {

new. next = pre.next.next;

pre.next = new;

}

(C) void insert (Listitem pre.Listitem new) {

if(pre.next == null) new.new = null;

pre.next = new;

}

(D) void insert (Listitem pre.Listitem new) {

new. Next = pre.next;

pre. Next = new;

}

63

NCUE CSIE Wireless Communications and Networking Laboratory

Question:

Given a linked list of values , we want to get a new list of

values that has the set of values in a reverse order. Write

one such algorithm reverse.

64

NCUE CSIE Wireless Communications and Networking Laboratory

Ans:

Procedure reverse(L: List pointer)

begin

q = nil;

p = L;

while (p≠nil) do

begin

r = q;

q = p;

p = p↑.Link;

q ↑.Link = r;

end;

L = q;

end;

65

NCUE CSIE Wireless Communications and Networking Laboratory

Question:

Please write a routine concat(&list1,&list2) the concatnates

two circular list.

Type of node and pointer is

struct node { type def strnct node *Nodeptr;

int info;

struct node *next;

}

66

NCUE CSIE Wireless Communications and Networking Laboratory

Ans:

void concat (Nodeptr *plist1, Nodeptr *plist2)

{

Nodeptr*p;

p= plist1→next;

plist1→Next=plist2→Next;

plist2→Next=p;

}

67

NCUE CSIE Wireless Communications and Networking Laboratory

Reference

Ellis Horowitz, Sartaj Sahni, and Susan Anderson-Freed

〝Fundamentals of Data Structures in C〞, W. H. Freeman & Co

Ltd, 1992.

Ellis Horowitz, Sartaj Sahni, and Dinesh Mehta

〝Fundamentals of Data Structures in C++〞 Silicon Pr, 2006

Richard F.Gilberg, Behrouz A. Forouzan,

〝Data Structures: A Pseudocode Approach with C〞, S

Baker & Taylor Books, 2004

Fred Buckley, and Marty Lewinter 〝A Friendly Introduction to Graph

Theory〞 Prentice Hall, 2002

〝資料結構-使用C語言〞蘇維雅譯,松崗,2004

〝資料結構-使用C語言〞 蔡明志編著,全華,2004

〝資料結構(含精選試題)〞洪逸編著,鼎茂,2005

68