《左耳听风》-ARTS-打卡记录-第十九周

《左耳听风》-ARTS-打卡记录-第十九周

Algorithm

剑指 Offer 24. 反转链表

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

示例:

输入: 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.完成一个番茄钟后,感觉自己要放松下.可以去做倒水,上厕所,点眼药,伸个懒腰,切换下办公桌,做下深呼吸这些事情,而非进到群里看看有啥事情.

Share

return和exit的区别

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CodingLife99

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值