鏈表原地置反

來源:互聯網
上載者:User
/* * 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;}

最近看自己以前寫的部落格,加上看過一些面試題,自己寫了一個採用遞迴方法,原地置反鏈表的程式,代碼如下:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.