《左耳听风》-ARTS-打卡记录-第十九周
Algorithm
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
题解:
给出一般的情况,三个相邻的元素h,i,j,想要保证i能够指向h,但之后还能够找到j,则需要先把j的位置给保存下来.此时需要用指针pPre,pNode和pNext来保存这三个位置,接着三个指针都向后移动,直到到达末尾.问题中提到反转后链表的头节点,它需要用例外的指针去保存.
需要考虑两种特殊情况,1是空列表,2是仅有一个元素的列表.
可以在解答之前先把测试用例想好,这样显得自己更专业.
进阶部分提了一个使用遍历方式来解答的问题,下次把这种情况实现下.下次不见不散.
代码:
#include <iostream>
using namespace std;
/*
* Definition for singly-linked list.
*/
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
//TestCases:
//1.Empty list
//2.a list with only one item
//3.a list with more than one item
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pNode = head;
ListNode* pPreNode = nullptr;
ListNode* pReversedHeader = nullptr;
while (pNode != nullptr)
{
ListNode* pNext = pNode->next; //get the next item first, in case the list break
if (pNext == nullptr) //includes the case of one item
{
pReversedHeader = pNode;
// no need to break,because when pNext == nullptr, pNode = pNext, will jump out of the loop.
}
pNode->next = pPreNode;
pPreNode = pNode;
pNode = pNext;
}
return pReversedHeader;
}
};
int main()
{
//how to create a List with val
ListNode *pl1 = new ListNode(1);
ListNode *pl2 = new ListNode(2);
ListNode *pl3 = new ListNode(4);
pl1->next = pl2;
pl2->next = pl3;
pl3->next = nullptr;
ListNode *pl = pl1;
while (pl != nullptr)
{
cout << pl->val;
pl = pl->next;
}
cout << endl;
Solution so;
ListNode * pReversedHeader = so.reverseList(pl1);
while(pReversedHeader != nullptr)
{
cout << pReversedHeader->val;
pReversedHeader = pReversedHeader->next;
}
cout << endl;
}
Review
Act with Prudence谨慎行动(97 Things Every Programmer Should Know 1/97)
Tips
1.画思维导图自己回忆去建立,而不要照抄去建立
2.选择不去关注屏蔽的微信群里的消息,既然被屏蔽了,说明既不紧急也不重要.
3.完成一个番茄钟后,感觉自己要放松下.可以去做倒水,上厕所,点眼药,伸个懒腰,切换下办公桌,做下深呼吸这些事情,而非进到群里看看有啥事情.