-
Notifications
You must be signed in to change notification settings - Fork 19
/
08-length-circular.c
68 lines (57 loc) · 1.4 KB
/
08-length-circular.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// 取得「環狀鍵結串列」長度
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
typedef struct node* Node;
void insertFront(Node* last, Node insertThis) {
if (!(*last)) {
*last = insertThis;
insertThis->next = insertThis;
} else {
insertThis->next = (*last)->next;
(*last)->next = insertThis;
}
}
Node createNode(int data) {
Node n = malloc(sizeof(*n));
n->data = data;
n->next = NULL;
return n;
}
int length(Node last) {
int count = 0;
Node current;
if (last) {
for (current = last->next; current != last; current = current->next) {
count++;
}
//最後一個會沒算到
count++;
}
return count;
}
int main() {
Node A = createNode(10);
Node B = createNode(20);
Node C = createNode(30);
Node D = createNode(40);
Node E = createNode(50);
Node F = createNode(60);
Node last = NULL;
insertFront(&last, A);
insertFront(&last, B);
insertFront(&last, C);
// C -> B -> A
printf("該環狀鍵結串列長度:%d\n", length(last));
insertFront(&last, D);
insertFront(&last, E);
insertFront(&last, F);
// F -> E -> D -> C -> B -> A
printf("該環狀鍵結串列長度:%d\n", length(last));
last = NULL;
printf("該環狀鍵結串列長度:%d\n", length(last));
return 0;
}