反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:
0 <= 节点个数 <= 5000
本题使用递归函数,一直递归到链表的最后一个结点,该结点就是反转后的头结点,记作 current.
此后,每次函数在返回的过程中,让当前结点的下一个结点的 next 指针指向当前节点。
同时让当前结点的next 指针指向 NULLNULL ,从而实现从链表尾部开始的局部反转
当递归函数全部出栈后,链表反转完成。
附加讨论区一个大神的图解:
代码:
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
if(head == null || head.next == null){
return head
}
else{
var current = reverseList(head.next);
//例如,1,2,3,4,5,null
//current是5
//head是4
//head.next 是 5
//head.next.next 就是5指向的指针,指向当前的head(4)
//5-4-3-2-1-null
head.next.next = head;
//注意把head.next设置为null,切断4链接5的指针
head.next = null
}
//每层递归返回当前的节点,也就是最后一个节点。(因为head.next.next改变了,所以下一层current变4,head变3)
return current;
};