本程式示範如何使用單向鏈表儲存未知數量的正整數,讀取至 -1 結束,再將鏈表反轉並依序輸出。此為《C語言程式設計進階(翁凱)》第五周編程作業參考解法,採用無哨兵節點的純指標操作。
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node *next;
} Node;
Node *add(Node *head, int number);
Node *inverse(Node *head);
void print(Node *head);
int main() {
Node *head = NULL;
int number;
while (scanf("%d", &number) && number != -1)
head = add(head, number);
head = inverse(head);
print(head);
return 0;
}
// 尾插法建立鏈表
Node *add(Node *head, int number) {
Node *p = (Node *)malloc(sizeof(Node));
p->value = number;
p->next = NULL;
Node *last = head;
if (last) {
while (last->next) last = last->next;
last->next = p;
} else {
head = p;
}
return head;
}
// 就地反轉鏈表(三指標法)
Node *inverse(Node *head) {
if (head != NULL && head->next != NULL) {
Node *p = head, *q = p->next, *tmp;
while (q->next) {
tmp = q->next;
q->next = p;
p = q;
q = tmp;
}
q->next = p;
head->next = NULL;
head = q;
}
return head;
}
// 列印並釋放記憶體
void print(Node *head) {
Node *p = head, *tmp;
if (p) {
while (p) {
printf("%d", p->value);
tmp = p;
p = p->next;
if (p) printf(" ");
else printf("\n");
free(tmp);
}
}
}
malloc 建立節點,free 釋放,避免記憶體洩漏。p, q, tmp 原地修改 next 指向,空間複雜度 O(1)。輸入:1 2 3 4 -1 輸出:4 3 2 1
此作業強化了指標操作、鏈表基本操作與記憶體管理,是 C 語言進階學習的重要里程碑。