連結串列 (Linked list)

連結串列 (Linked list)

連結串列 教學與筆記。

struct 實現

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
69
70
71
72
73
74
75
76
77
78
#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

void push(struct Node** head_ref, int new_data){
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node -> data = new_data;
new_node -> next = *head_ref;
(*head_ref) = new_node;
}

void print_list(struct Node* node){
while(node != NULL){
printf("%d ", node->data);
node = node -> next;
}
printf("\n");
}

void reverse(struct Node** head_ref){
struct Node* prev = NULL;
struct Node* curr = *head_ref;
struct Node* next = NULL;
while(curr != NULL){
// Notice below loop relations
next = curr -> next; // Store next first
curr -> next = prev;
prev = curr;
curr = next;
}
*head_ref = prev;
}

void delete(struct Node** head_ref, int input){
// Delete all occurrences input num
struct Node* prev = NULL;
struct Node* curr = *head_ref;

// If head node is input
if(curr -> data == input){
*head_ref = curr -> next;
free(curr);
curr = *head_ref;
}

// Search input in the middle of list
while(curr != NULL){
if(curr -> data == input){
prev -> next = curr -> next;
free(curr);
curr = prev -> next;
}
else {
prev = curr;
curr = curr -> next;
}
}
}

void main() {
struct Node* head = NULL;
push(&head, 3);
push(&head, 4);
push(&head, 2);
push(&head, 3);
push(&head, 1);
print_list(head); // 1 3 2 4 3

reverse(&head);
print_list(head); // 3 4 2 3 1

delete(&head, 3);
print_list(head); // 4 2 1
}
Author

Meow Lucian

Posted on

2019-06-27

Updated on

2022-07-06

Licensed under

Comments