1. 程式人生 > >C語言反轉鏈表

C語言反轉鏈表

return ret while printf truct free 語言 使用 ever

原創文章,拒絕轉載

主要的思想是使用三個標記指針: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語言反轉鏈表