先輸入整數個數 N,接著輸入 N 個整數,要求依照輸入的相反順序建立單向鏈結串列,最後依序輸出串列中的資料。
第一行是整數 N;第二行依序給出 N 個整數。輸出即為逆序排列後的鏈結串列內容。
示例輸入:
10
11 3 5 27 9 12 43 16 84 22
示例輸出:
22 84 16 43 12 9 27 5 3 11
關鍵在於「頭插法」:每讀入一個新節點就掛到頭節點之後,如此一來 naturally 形成逆序。程式碼如下:
#include <iostream>
#include <malloc.h>
using namespace std;
struct biao {
int data;
struct biao *next;
};
void shu_ru(struct biao *head, int n) {
for (int i = 1; i <= n; i++) {
struct biao *p = (struct biao *)malloc(sizeof(struct biao));
cin >> p->data;
p->next = head->next;
head->next = p;
}
}
void shu_chu(struct biao *head) {
cout << head->next->data;
head = head->next;
while (head->next) {
cout << " " << head->next->data;
head = head->next;
}
}
int main(void) {
struct biao *head = NULL;
head = (struct biao *)malloc(sizeof(struct biao));
head->next = NULL;
int t;
cin >> t;
shu_ru(head, t);
shu_chu(head);
return 0;
}
這份解答已通過 SDUT OJ 2117,記憶體用量約 464K,執行時間 0MS。