/* * reverse_list.cpp * * Created on: 2012-5-22 * Author: ict */#include <cstdio>#include <cstring>#include <cstdlib>using namespace std;//定義結構體typedef struct NODE{int data;struct NODE *next;}*PNode, NODE;/* * 核心函數 * 輸入:鏈表的頭指標 * 輸出:鏈表置反後的尾指標,其實就是頭指標head,但是順序已經改變,head已經變成了tail */PNode reverse(PNode head){PNode tail;if (head->next == NULL)//最後一個節點,直接返回return head;else//否則遞迴調用{tail = reverse(head->next);tail->next = head;head->next = NULL;return head;}}int main(){int n;int i;int temp;PNode head;PNode tail, q;tail = NULL;head = (PNode) malloc(sizeof(NODE));head->next = NULL;printf("Please input the number:");scanf("%d", &n);for (i = 0; i < n; i++){scanf("%d", &temp);q = (PNode) malloc(sizeof(NODE));q->data = temp;q->next = NULL;if (tail != NULL)tail->next = q;tail = q;if (i == 0){head->next = q;}}q = head->next;for (i = 0; i < n; i++){printf("%d ", q->data);q = q->next;}printf("\n");reverse(head->next);for (i = 0; i < n; i++){printf("%d ", tail->data);tail = tail->next;}printf("\n");return 0;}
最近看自己以前寫的部落格,加上看過一些面試題,自己寫了一個採用遞迴方法,原地置反鏈表的程式,代碼如下: