C語言反轉鏈表

來源:互聯網
上載者:User

標籤:null   node   ++   printf   return   nod   main   std   sizeof   

原創文章,拒絕轉載

主要的思想是使用三個標記指標:preNode、curNode、nextNode,每次將curNode的next設為preNode,然後如果此時nextNode為空白,跳出迴圈,將鏈表頭指標的next設為NULL,返回鏈表尾指標;否則,preNode = curNode,curNode=nextNode,nextNode=nextNode -> next。

實現如下:

#include <stdio.h>#include <malloc.h>typedef struct Node{    int val;    struct Node *next;} Node;Node* reverse_list(Node *headNode) {    if (headNode == NULL) {        return NULL;    }    if (headNode -> next == NULL) {        return headNode;    }    if (headNode -> next -> next == NULL) {        Node* resNode = headNode -> next;        resNode -> next = headNode;        headNode -> next = NULL;        return resNode;    }    Node *preNode = headNode;    Node *curNode = preNode -> next;    Node *nextNode = curNode -> next;    for ( ; ; ) {        curNode -> next = preNode;        if (nextNode == NULL) {            break;        }        preNode = curNode;        curNode = nextNode;        nextNode = curNode -> next;    }    headNode -> next = NULL;    return curNode;}int main(int argc, char const *argv[]){    int n;    int temp;    int i;    scanf("%d", &n);    if (n <= 0)        return 0;        Node* headNode = (Node*)malloc(sizeof(Node));    scanf("%d", &temp);    headNode -> val = temp;    headNode -> next = NULL;    Node *curNode = headNode;    for (i = 1; i < n; i++) {        scanf("%d", &temp);        curNode -> next = (Node*)malloc(sizeof(Node));        curNode -> next -> val = temp;        curNode -> next -> next = NULL;        curNode = curNode -> next;    }    curNode = reverse_list(headNode);    Node *tempNode;    while (curNode) {        tempNode = curNode;        curNode = curNode -> next;        printf("%d ", tempNode -> val);        free(tempNode);    }    printf("\n");    return 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.