例一:链表创建
单向链表:
- 只能往后指,不能往前看
- 通过考察链表 = 考察敲代码能力
递归:
严格定义函数的作用:
- 给一个数组,把数组每个元素生成一个节点,
- 把节点首尾相接
- 链表必须以null结尾
- 把第一个节点作为链表头
这样:
- 用户可以拿着链表头,可以一直顺着它的next,访问到链表结尾
- 看到null之后,说明链表结束了
怎么缩小问题的规模:
- 定义一个函数CreateLinkedList
- 它的返回值node(链表的头)
输入本来是12345
把1拆掉,把2345去建一个LinkedList
把1和2345接起来
怎么接的?
2345运行完CreateLinkedList,少了一个结点1
把1的next和2345返回的头(head)接起来
完成了链表的创建
进入代码:
欢迎大家去GitHub下载java文件
一大串代码,不好展示(注释比较多,主要是理清逻辑思路,但是平时是不用注释那么多哦!)
如果喜欢的请慷慨的star一下吧~谢谢啦❤
【免费啦!给个小星星嘛~】
解释注释:
/**
* Creates a linked list.
*
* @param data
* the data to create the list
* @return head of the linked list.The returned linked list ends with last node
* with getNext() == null.【基准】
*/
Creates a linked list.
创建一个链表。
@param data the data to create the list
the data to create the list:创建列表的数据
@return head of the linked list.
返回值是head of the linked list(链表的头)
The returned linked list ends with last node with getNext() == null
linked list有一条隐性的规定:在函数的本体里显示不出来,但是要在这里规定好——>返回的linked list的最后一个节点的getNext()必须等于null。
细节转换:
Node headOfSublist = creatLinkedList(data.subList(1, data.size()));
firstNode.setNext(headOfSublist);
可以变成:
firstNode.setNext(creatLinkedList(data.subList(1, data.size())));