剑指offer反转链表(C++实现|测试用例|迭代法和递归法)
方法1:迭代法
代碼:
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode*cur = NULL;
ListNode*pre = head;
if(head == NULL||head->next==NULL)
{
return head;
}
while(pre!=NULL)
{
ListNode* p = pre->next;
pre->next = cur;
cur = pre;
pre = p;
}
return cur;
}
};
int main()
{
ListNode* head = new ListNode(1);
ListNode* sec = new ListNode(4);
ListNode* thr = new ListNode(5);
ListNode* fou = new ListNode(9);
head->next = sec;
sec->next = thr;
thr->next = fou;
fou->next = nullptr;
Solution s;
ListNode*p_head = s.reverseList(head);
while(p_head!=nullptr)
{
cout <<p_head->val<<endl;
p_head = p_head->next;
}
}
方法2:遞歸
代碼:
ListNode* reverseList_1(ListNode* head)
{
if(head==NULL||head->next==NULL)
{
return head;
}
ListNode* cur = reverseList_1(head->next);
head->next->next = head;
head->next = NULL;
return cur;
}
?
總結
以上是生活随笔為你收集整理的剑指offer反转链表(C++实现|测试用例|迭代法和递归法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++类的静态成员详解
- 下一篇: c++ 回调函数与std::functi