单向链表翻转
Posted veis
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单向链表翻转相关的知识,希望对你有一定的参考价值。
#include <stdio.h> #include <stdlib.h> typedef struct ListNode { int val; struct ListNode *next; }ListNode; ListNode* ReverseList(ListNode* pHead) { if (pHead == NULL) return pHead; ListNode* pre = NULL; ListNode* cur = pHead; ListNode* nxt = NULL; ListNode* res = NULL; while (cur != NULL) { nxt = cur->next; cur->next = pre; if (nxt == NULL) break; pre = cur; cur = nxt; } return cur; } int main() { int i = 0; ListNode *pHead = NULL; while (i <= 5) { ListNode *pNew = (ListNode *)malloc(sizeof(ListNode)); pNew->val = i++; pNew->next = pHead; pHead = pNew; } pHead = ReverseList(pHead); while (pHead) { printf("%d ", pHead->val); pHead = pHead->next; } system("pause"); return 0; }
以上是关于单向链表翻转的主要内容,如果未能解决你的问题,请参考以下文章