Solution:
这个题首先不要一上来就想着使用栈或者递归,而是应该想着如何利用最基本的指针来解决这个问题。
此题解题思路为:使用三个指针pre cur nex来实现对于每一个结点的next修改方向(可以验证,刚好要三个指针才能实现),最后遍历即可,时间复杂度为O(n) 。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode *pre=nullptr;//nullptr代表空指针
ListNode *cur=pHead;// 获取一个当前指针
ListNode *nex=nullptr;//后指针
//这种解法才是最需要学习的,三个指针实现,不能像之前想当然的直接改下一个指针域,这样就遍历不走成死循环了。
while(cur){
nex=cur->next;
cur->next=pre;
pre=cur; //实现反转
cur=nex; //继续往后走直到遍历结束
}
return pre;
}
};
常见的错误思路是直接写
while(p){
p->next->next=p;
p=p->next;
}
这样的写法会导致程序死循环卡死。