题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* ReverseList(ListNode* pHead) { while(!pHead || !pHead->next) return pHead; ListNode *pre, *cur, *nex; pre = NULL; cur = pHead; while(cur) { nex = cur->next; cur->next = pre; pre = cur; cur = nex; } return pre; } };
三指针最简单思路,pre最开始指向NULL,cur为当前需要修改链接的节点,nex记录下一个待遍历节点
顺序为:
nex先记录cur的后继节点,
断开指针指向前节点pre,
pre前移指向cur,cur前移指向nex