例二:链表反转
【思路】先把2345链表反转
假设函数能够正确反转链表【假设很重要】
反转之后,元素1的next指向哪里呢?
仍然指向元素2
【细节】
反转没有碰到元素1本身,只是把2开头的链表进行了反转
接下来要做的事:
1开头的链表也能正确反转
怎么做?
把2的next指向1
把1的next指向null
敲代码原则:
精确描述:
/**
* Reverses a linked list.
*
* @param head
* the linked list to reverse
* @return head of the reversed linked list
*/
干什么的?
Reverses a linked list.
反转链表
Head指向?
the linked list to reverse
要反转的链表
返回的是什么?
head of the reversed linked list
反转链表的头
(把反转完的linked list的head return出来)
当然:
linked list仍然需要以null结尾
图解:
反转之后就是这样:
从数学归纳法的角度:
Size == 1是数学归纳法的基础(自然数从1开始)
size == 0是数学归纳法的特例
代码简化:
//特殊值(1)
if (head == null)// 链表里什么都没有【size == 0】
{
return null;
}
//特殊值(2)
if (head.getNext() == null)// 链表只有1个结点:head本身【size == 1】
{
把Size == 1和size == 0合起来:
if (head == null || head.getNext() == null)
{
return head;
}
输出结果:
写递归函数的关键:
对【N-1】的情况正确输出
- 返回值正确
- 结构完整正确(把2开头的链表反转以后,必须完整)
开源代码在这里
CheeseCheese-IScream
给个小星星啦❤