Presentation is loading. Please wait.

Presentation is loading. Please wait.

Software Learning Resource Service Platform CHAPTER 4 鏈結串列 (Linked List) 1.

Similar presentations


Presentation on theme: "Software Learning Resource Service Platform CHAPTER 4 鏈結串列 (Linked List) 1."— Presentation transcript:

1 Software Learning Resource Service Platform CHAPTER 4 鏈結串列 (Linked List) 1

2 Software Learning Resource Service Platform Introduction  陣列 : 使用陣列來循序對應,以連續空間來儲存  缺點 : 若要加入或刪除某一節點,較耗時間  改善方法 : Linked list 2

3 Software Learning Resource Service Platform Pointer Can Be Dangerous 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 */ 3

4 Software Learning Resource Service Platform Dynamically Allocated 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 4

5 Software Learning Resource Service Platform Singly Linked Lists 單向鏈結串列 5

6 Software Learning Resource Service Platform Insertion 6

7 Software Learning Resource Service Platform Delete mat from list Deletion 7

8 Software Learning Resource Service Platform 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

9 Software Learning Resource Service Platform address of first node ptr data ptr link e -> name  (*e).name strcpy(ptr -> data, “bat”); ptr -> link = NULL; 9

10 Software Learning Resource Service Platform 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

11 Software Learning Resource Service Platform 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

12 Software Learning Resource Service Platform 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

13 Software Learning Resource Service Platform temp->data = 50; if (*ptr) { noempty list temp->link =node ->link; node->link = temp; } else { empty list temp->link = NULL; *ptr =temp; } } 13

14 Software Learning Resource Service Platform (a) before deletion (b)after deletion Delete node other than the first node. List Deletion Delete the first node. 14

15 Software Learning Resource Service Platform 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

16 Software Learning Resource Service Platform 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

17 Software Learning Resource Service Platform Dynamically Linked stacks and queues    17

18 Software Learning Resource Service Platform 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

19 Software Learning Resource Service Platform 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

20 Software Learning Resource Service Platform 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

21 Software Learning Resource Service Platform 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

22 Software Learning Resource Service Platform Add 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; } 22

23 Software Learning Resource Service Platform Delete 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; } 23

24 Software Learning Resource Service Platform Polynomials typedef struct poly_node *poly_pointer; typedef struct poly_node { int coef; int expon; poly_pointer link; }; poly_pointer a, b, c; coefexponlink 24

25 Software Learning Resource Service Platform Examples 25

26 Software Learning Resource Service Platform Add 26

27 Software Learning Resource Service Platform 27 Add

28 Software Learning Resource Service Platform 28 Add

29 Software Learning Resource Service Platform Algorithm(Add) 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)) { 29

30 Software Learning Resource Service Platform case -1: /* a->expon 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

31 Software Learning Resource Service Platform Analysis (1)coefficient additions 0  additions  min(m, n) where m (n) denotes the number of terms in A (B). (2)exponent comparisons extreme case e m-1 > f m-1 > e m-2 > f m-2 > … > e 0 > f 0 m+n-1 comparisons (3)creation of new nodes extreme case m + n new nodes summary: O(m+n) 31

32 Software Learning Resource Service Platform Attach a Term 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; } 32

33 Software Learning Resource Service Platform A Suite for Polynomials poly_pointer a, b, d, e;. a = read_poly(); b = read_poly(); d = read_poly(); temp = pmult(a, b); e = padd(temp, d); print_poly(e); read_poly() print_poly() padd() psub() pmult() temp is used to hold a partial result.By returning the nodes of temp, wemay use it to hold otherpolynomials 33

34 Software Learning Resource Service Platform Erase 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) 34

35 Software Learning Resource Service Platform Circularly Linked Lists circular list vs. chain 35

36 Software Learning Resource Service Platform Maintain an Available List 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; } 36

37 Software Learning Resource Service Platform 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 37

38 Software Learning Resource Service Platform Representing Polynomials as Circularly Linked Lists 38

39 Software Learning Resource Service Platform Head Node Represent polynomial as circular list. (1) zero (2) others 39

40 Software Learning Resource Service Platform 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 40

41 Software Learning Resource Service Platform 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 41

42 Software Learning Resource Service Platform Additional List Operations typedef struct list_node *list_pointer; typedef struct list_node { char data; list_pointer link; }; Invert single linked lists Concatenate two linked lists 42

43 Software Learning Resource Service Platform 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. 43

44 Software Learning Resource Service Platform 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 44

45 Software Learning Resource Service Platform Operations For Circularly Linked List What happens when we insert a node to the front of a circular linked list? Problem: move down the whole list. 45

46 Software Learning Resource Service Platform A possible solution: Note a pointer points to the last node. 46

47 Software Learning Resource Service Platform Operations for Circularly Linked Lists void insert_front (list_pointer *ptr, list_pointer node) { if (IS_EMPTY(*ptr)) { /* list is empty, chang ptr to point to new entry */ *ptr= node; node->link = node; } else { /* list is not empty, add new entry at front */ node->link = (*ptr)->link; (1) (*ptr)->link = node; (2) } 47

48 Software Learning Resource Service Platform Length of 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; } 48

49 Software Learning Resource Service Platform Equivalence Relations 49 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

50 Software Learning Resource Service Platform 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} 50

51 Software Learning Resource Service Platform A Rough Algorithm to Find Equivalence Classes void equivalence() { initialize; while (there are more pairs) { read the next pair ; process this pair; } initialize the output; do output a new equivalence class; while (not done); } What kinds of data structures are adopted? 51

52 Software Learning Resource Service Platform First Refinement { initialize seq to NULL and out to TRUE while (there are more pairs) { read the next pair, ; 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 52

53 Software Learning Resource Service Platform Lists after pairs are input [ 0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] seq NULL 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 11 3 5 1 7 0 3 8 10 46 9 86 0 2 4 11 53

54 Software Learning Resource Service Platform 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; } 54

55 Software Learning Resource Service Platform /* 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 55

56 Software Learning Resource Service Platform /* 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 56

57 Software Learning Resource Service Platform 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 57

58 Software Learning Resource Service Platform Revisit Sparse Matrices 開頭節點 元素節點 連同一列元素 58 Set up for a ij

59 Software Learning Resource Service Platform Linked Representation for Matrix 59

60 Software Learning Resource Service Platform 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 ( ) 60

61 Software Learning Resource Service Platform 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 61

62 Software Learning Resource Service Platform Empty doubly linked circular list with head node 62

63 Software Learning Resource Service Platform Insertion into an empty doubly linked circular list 63

64 Software Learning Resource Service Platform 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; } 64

65 Software Learning Resource Service Platform 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); } 65

66 Software Learning Resource Service Platform 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; } 66 Question:

67 Software Learning Resource Service Platform (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; } 67

68 Software Learning Resource Service Platform (1)Describe all operations associated with a single and a doubly linked lists. (2)Compare the differences of insertion methods for both data structures. Ans: (1) 兩者均有 insert( 插入一個新的 node) 及 delete( 刪除一個 node) 68 Question:

69 Software Learning Resource Service Platform (2) 69 Single Link ListDouble Link List 1. 僅知一個方向的節點位置 1. 知道兩個方向的節點位置 2. 須從頭開始搜尋才能搜尋 到所有節點 2. 任何一點皆可搜尋到所有 節點的位置 3. 刪除其中一個節點,須先 告知此節點的前個節點位置 3. 刪除其中一個節點,不需 要告知前個節點位置在何處 4. 可靠度低 4. 可靠度較高 1. 插入節點較容易 ( 只需改兩 個指標 ) 1. 插入節點比較困難 ( 需要改 變四個指標 ) 2. 刪除節點較容易 ( 只需改一 個指標 ) 2. 刪除節點較困難 ( 需要改變 兩個指標 ) 3. 較節省空間 3. 較浪費空間

70 Software Learning Resource Service Platform 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. 70 Question:

71 Software Learning Resource Service Platform 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; 71

72 Software Learning Resource Service Platform Given a circular list with n items, what are the time complexities for the following operations? ( 一 )Inserting a new item before the item pointed to by a given pointer. ( 二 )Inserting a new item after the item pointed to by a given pointer. 72 Question:

73 Software Learning Resource Service Platform Ans: ( 一 ) 先搜尋到該指定 ITEM 及 item 之前一個 node ,時間複 雜度為 O(n) 。將新 node 之鏈結指向該 ITEM ,時間複 雜度為 O(1) 。將 item 前一個 node 之指標改指向新 ITEM ,時間複雜度為 O(1) 。所以此項 operation 之時間 複雜度為 O(n) 。 ( 二 )O(1) 73

74 Software Learning Resource Service Platform 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; } 74 Question:

75 Software Learning Resource Service Platform Ans: void concat (Nodeptr *plist1, Nodeptr *plist2) { Nodeptr*p; p= plist1 → next; plist1 → Next=plist2 → Next; plist2 → Next=p; } 75

76 Software Learning Resource Service Platform Please compare the functions of the 〝 Sequential List 〞 and 〝 Linked List 〞 data structctures in terms of their advantages and disadvantages. 76 Question:

77 Software Learning Resource Service Platform Ans: 77 Sequential ListLinked List advantages  可支援 Random Access 及 Sequential Access  循序讀取速度快  可靠度較高  Insert , Delete node 花 O(1)  資料 size 可任意擴充  各 node 可以不連結存於 memory 中,各 node 之 type 可以不同  合併兩串列容易 disadvantages  插入、刪除不便,花 O(n)  Data 串列不易動態擴充  串列之合併,分裂不易  僅支援 Sequential Access , 不支援 Random Access  可靠度差  循序讀取慢

78 Software Learning Resource Service Platform Explain the following terms: ( 一 )Ordered linked list ( 二 )Variant record 78 Question:

79 Software Learning Resource Service Platform Ans: ( 一 ) 為表示 order list 之 data structure ,由一組 node 所構成。 每一 node 除了 data 欄外,另包含 link 欄 (pointer) 用以指向其 它 nodes 。 ( 二 ) Variant record 為一 ecord 具有變動欄值,意指此欄位的結 構型態並不固定。 79

80 Software Learning Resource Service Platform 80 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


Download ppt "Software Learning Resource Service Platform CHAPTER 4 鏈結串列 (Linked List) 1."

Similar presentations


Ads by Google