C++:Leetcoed-链表-206反转链表
熟悉链表的使用
加强对链表指针的理解,加强对双指针用法的理解
题目
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
有两种解法思路,双指针法和递归法
先介绍双指针法,递归法后续补上
双指针法
/*
Leetcode-206反转链表
1、双指针法
2、递归法
*/
#include "iostream"
#include "vector"
using namespace std;
//创建节点
class ListNode
{
public:
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *l_next) : val(x), next(l_next) {}
};
//创建链表类
class myLinkedList
{
public:
int listSize;
ListNode *dummyNode; //虚拟头结点
public:
//构造函数初始化
myLinkedList()
{
listSize = 0;
dummyNode = new ListNode(0); //创建虚拟头节点
}
//创建链表
ListNode *createList(vector<int> &nums)
{
ListNode *current = new ListNode(nums[0]);
dummyNode->next = current;
for (int i = 1; i < nums.size(); i++)
{
current->next = new ListNode(nums[i]);
current = current->next;
}
listSize += nums.size();
}
//打印链表
void printList()
{
ListNode *current = dummyNode->next;
while (current != nullptr)
{
cout << current->val << "\t";
current = current->next;
}
cout << endl;
}
//打印反转后链表
void printReverseList(ListNode *head)
{
ListNode *current = head;
while (current != nullptr)
{
cout << current->val << "\t";
current = current->next;
}
cout << endl;
}
};
//双指针法
//重点还是对于指针的理解
class Solution
{
public:
ListNode *reverseList(ListNode *head)
{
ListNode *pre = nullptr;
ListNode *cur = head;
ListNode *temp;
while (cur != nullptr)
{
temp = cur->next; //方便后续cur指针的移动
cur->next = pre;
pre = cur;
cur = temp; //此处cur = cur->next,cur = pre->next都是错误!!!重点理解!!!!
//因为cur->next 此时也被pre赋值,并不是真正意义的next,
//pre此时与cur相同,所以pre->next==cur->next 一样是移动上来的pre,不是真正next
//所以需要temp来存cur->next
}
return pre; //cur为nullptr,pre才是反转后头结点
}
};
int main(int argc, const char **argv)
{
myLinkedList mylist;
vector<int> nums = {1, 2, 3, 4, 5, 6};
mylist.createList(nums);
mylist.printList();
Solution s1;
ListNode *reverseNode;
reverseNode = s1.reverseList(mylist.dummyNode->next);
mylist.printReverseList(reverseNode);
return 0;
}
总结
链表的熟练运用,双指针法的熟悉
参考代码随想录