今天研究了一下反转链表,头都快绕晕了,简单总结一下就是要有三个变量
pre,cur,next
LinkNode* pre,cur,next;
//其中pre指向 反转数字的前一个
//因此 cur = pre->next
//next = cur->next
//找到next
next = cur->next
//删除next,接下来要将next指向cur(pre->next)
cur->next = next->next
//将next指向cur
next->next = pre->next
//将pre指向next
pre->next = next
上面这种做法只需要遍历一遍就可以了
或者呢 我们可以单独去反转链表
这样,需要遍历两边
这一次我们需要找到反转链表左边的前一位pre
,以及右边那位RightNode
然后就去将链表断开
ListNode* LeftNode = pre->next;
//代表分割后的那段链表的头
ListNode* cur = RightNode->next;
//在函数传入LeftNode
reverseLinkList(LeftNode)
{
ListNode* pre = nullptr;
ListNode* cur = LeftNode;
while(cur!=nullptr)
{
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
}
//函数退出后,再次链接起来
pre->next = RightNode;
LeftNode->next = cur;