單向鏈表是動態資料結構基礎。本文提供完整、可編譯的 C 語言實作,涵蓋所有核心操作,採用「帶頭結點」設計簡化邊界處理。
typedef struct Node {
int data;
struct Node *next;
} Node;
typedef struct {
Node *head; /* 頭結點 (不存資料) */
int size;
} List;
void initList(List *list) {
list->head = (Node *)malloc(sizeof(Node));
list->head->next = NULL;
list->size = 0;
}
void createList(List *list, int n) {
Node *tail = list->head;
for (int i = 0; i < n; i++) {
int val; scanf("%d", &val);
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = val;
newNode->next = NULL;
tail->next = newNode;
tail = newNode;
list->size++;
}
}
bool insertList(List *list, int pos, int val) {
if (pos < 0 || pos > list->size) return false;
Node *prev = list->head;
for (int i = 0; i < pos; i++) prev = prev->next;
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = val;
newNode->next = prev->next;
prev->next = newNode;
list->size++;
return true;
}
bool deleteList(List *list, int pos) {
if (pos < 0 || pos >= list->size) return false;
Node *prev = list->head;
for (int i = 0; i < pos; i++) prev = prev->next;
Node *del = prev->next;
prev->next = del->next;
free(del);
list->size--;
return true;
}
int findList(List *list, int val) {
Node *cur = list->head->next;
int idx = 0;
while (cur) {
if (cur->data == val) return idx;
cur = cur->next;
idx++;
}
return -1;
}
void printList(List *list) {
Node *cur = list->head->next;
while (cur) {
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}
void destroyList(List *list) {
Node *cur = list->head;
while (cur) {
Node *next = cur->next;
free(cur);
cur = next;
}
list->head = NULL;
list->size = 0;
}
int main() {
List list; initList(&list);
createList(&list, 5); /* 輸入: 1 2 3 4 5 */
printList(&list); /* 1 2 3 4 5 */
insertList(&list, 2, 99); /* 1 2 99 3 4 5 */
printList(&list);
deleteList(&list, 0); /* 2 99 3 4 5 */
printList(&list);
printf("Find 99: %d\n", findList(&list, 99)); /* 1 */
destroyList(&list);
return 0;
}