反轉鏈表
反轉鏈表
輸入一個鏈表的頭節點,反轉該鏈表並輸出反轉後鏈表的頭節點。
思路:定義3個指針,分別指向當前節點,它的前一個節點,它的後一個節點。
參考代碼:
root@gt:/home/git/Code# ./a.out begin:9 8 7 6 5 4 3 2 1 0 after:0 1 2 3 4 5 6 7 8 9 root@gt:/home/git/Code# cat reverseList.c #include <stdio.h>#include <stdlib.h>#include <string.h>typedef struct listNode{ int value; struct listNode* pnext;}ListNode;ListNode* reverseList(ListNode* phead){ ListNode* pPrev = NULL; ListNode* pCurr = phead; ListNode* pNext = NULL; ListNode* pRhead = NULL; while(pCurr != NULL) { pNext = pCurr->pnext; if(pNext == NULL) pRhead = pCurr; pCurr->pnext = pPrev; pPrev = pCurr; pCurr = pNext; } return pRhead;}int main(){ ListNode* phead = NULL; printf("begin:
"); for(int i = 0;i < 10;i++) { ListNode* pnew = (ListNode*)malloc(sizeof(ListNode)); pnew->value = i; pnew->pnext = phead; phead = pnew; } ListNode* ptmp = phead; for(int i = 0;i < 10;i++) { printf("%d ",ptmp->value); ptmp = ptmp->pnext; } printf("
after:
"); ListNode* pRhead = reverseList(phead); ptmp = pRhead; for(int i = 0;i < 10;i++) { printf("%d ",ptmp->value); ptmp = ptmp->pnext; } printf("
"); return 0;}
推薦閱讀: