剛把資料結構的單向鏈表過了一輪,趁記憶還熱,把建立、插入、刪除、反轉這幾個基本操作整理成一份可運行的範例。這裡重在把指標操作的思路講清楚,部分資料結構的細節並未嚴謹展開;由於是初學之作,程式碼寫得比較直白,若有更好的寫法也歡迎指教。
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
} head;
struct node *p, *q; /* 暫存節點 */
void head_insert(int x) { /* 從頭部插入 */
p = (struct node *)malloc(sizeof(struct node));
if (p == NULL) {
printf("記憶體申請失敗,退出");
exit(0);
}
p->data = x;
p->next = head.next;
head.next = p;
}
void tail_insert(int x) { /* 從尾端插入 */
p = (struct node *)malloc(sizeof(struct node));
if (p == NULL) {
printf("記憶體申請失敗,退出");
exit(0);
}
p->data = x;
p->next = NULL;
q->next = p;
q = p;
}
void node_length() { /* 輸出鏈表長度 */
int length = 0;
p = head.next;
if (p == NULL)
printf("The length of node is 0.\n");
else {
do {
length++;
p = p->next;
} while (p);
printf("The length of node is %d.\n", length);
}
}
void print_node() { /* 列印鏈表 */
printf("輸出此時鏈表:\n");
p = head.next;
if (p == NULL) { printf("NULL\n"); return; }
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void clear_node() { /* 清空鏈表 */
p = head.next;
head.next = NULL;
while (p) {
q = p;
p = p->next;
free(q);
}
}
void new_insert(int i, int a) { /* 在第 i 個位置後插入 a */
q = (struct node *)malloc(sizeof(struct node));
q->data = a;
p = head.next;
if (i < 0)
printf("Position Error.\n");
else {
while (p && --i) p = p->next;
if (i)
printf("Position Error.\n");
else {
q->next = p->next;
p->next = q;
}
}
}
void delete_node(int i) { /* 刪除第 i 個節點 */
p = &head;
while (p->next && --i) p = p->next;
if (i)
printf("Position Error.\n");
else {
q = p->next;
p->next = q->next;
free(q);
}
}
void invert_order() {
struct node *This, *prev;
p = head.next;
This = NULL;
while (p) {
prev = This;
This = p;
p = p->next;
This->next = prev; /* 每走一步就把箭頭掉頭 */
}
head.next = This;
}
反轉的精髓只有一句:先把 next 存起來,再把指標指向上一個節點。三個指標交替推進,一趟迴圈就完成,不需要額外陣列。
int main() {
int number, i, a;
head.next = NULL;
q = &head;
printf("輸入整型資料:\n");
while (scanf("%d", &number) != EOF)
head_insert(number); /* 頭插即為逆序建立 */
invert_order();
node_length();
print_node();
printf("在第 i 個位置後插入 a,請輸入 i 和 a:\n");
scanf("%d%d", &i, &a);
new_insert(i, a);
print_node();
printf("輸入要刪除的第 i 個結點:\n");
scanf("%d", &i);
delete_node(i);
print_node();
clear_node();
return 0;
}
補充一個實用技巧:Windows 下輸入完畢後按 Enter,再按 Ctrl+Z,最後再按 Enter 即可送出 EOF;Linux 下則直接按 Ctrl+D。