編程演算法 - 鏈表逆序 代碼(C)

來源:互聯網
上載者:User

標籤:mystra   編程演算法   鏈表逆序   非遞迴   c++   

鏈表逆序 代碼(C)


本文地址: http://blog.csdn.net/caroline_wendy


鏈表逆序, 作為鏈表操作的基礎必須要熟練手寫.

主要包含3個部分, 一個指標記錄後面節點, 一個指標記錄前面節點, 把當前節點指到前面節點, 移動到後面節點, 前後指標依次移動.

非遞迴鏈表逆序演算法的核心代碼只有10行.


代碼:

/* * main.cpp * *  Created on: 2014.9.12 *      Author: Spike *//*eclipse cdt, gcc 4.8.1*/#include <stdio.h>#include <stdlib.h>struct ListNode{    int data;    ListNode* next;};void PrintList(ListNode* head);ListNode* ReverseList(ListNode* head);int main(){ListNode* head = new ListNode();ListNode* node1 = new ListNode();ListNode* node2 = new ListNode();ListNode* node3 = new ListNode();ListNode* node4 = new ListNode();head->data = 0;head->next = node1;node1->data = 1;node1->next = node2;node2->data = 2;node2->next = node3;node3->data = 3;node3->next = node4;node4->data = 4;node4->next = NULL;PrintList(head);ListNode* re = ReverseList(head);PrintList(re);return 0;}ListNode* ReverseList(ListNode* head){    if(head == NULL || head->next == NULL) {       return head;   /*鏈表為空白或只有一個元素則直接返回*/    }    ListNode* prev = NULL;    ListNode* next = NULL;    while (head != NULL) {    next = head->next;    head->next = prev;    prev = head;    head = next;    }    return prev;}void PrintList(ListNode* head){    while(head != NULL)    {        printf("%d ", head->data);        head = head->next;    }    printf("\n");}

輸出:

0 1 2 3 4 4 3 2 1 0 







編程演算法 - 鏈表逆序 代碼(C)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.