反转链表
非递归迭代解法
非递归:
需要三个临时指针;
pPrev指向前一个的指针,pnode用来遍历链表的指针,preversedhead用来保存链表的尾节点;循环遍历的时候首先将pNext保存下来,迭代节点指向前一个节点,更新pPre,迭代下一个节点
代码:
#include <iostream>
using namespace std;
ListNode *ReverseList(ListNode *pHead)
{
ListNode *pReverseNode = nullptr;
ListNode *pNode = pHead;
ListNode *pPre = nullptr;
while(pNode != nullptr){
ListNode *pNext = pNode->m_pNext;
if(pNext == nullptr)
pReverseNode = pNode;
pNode->m_pNext = pPre;
pPre = pNode;
// go to next Node
pNode = pNext;
}
}
递归版本
用到了函数栈,当递归到底的时候,会从最后一个结点依次返回到函数中,函数中依次保存节点。
代码:
// 递归版本
ListNode* reverseList(ListNode* head) {
if(!head || !head->next) return head;
ListNode* newhead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newhead;
}
链表中倒数第k个节点
方法:双指针,第一个指针先走k-1步,此时第二个指针开始走,如果第一个指针走到
最后,第一个指针就是倒数第k个指针。