题目:定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL、
解题思路:
- 当节点数为0或者为1的时候直接返回头结点
- 当节点数为2的时候,例如5->4->null,此时需要返回的根节点是4,因此先将4保存下来,使4的下一个节点为5即head.next.next = head;再使5指向null即head.next = null;
- 当根节点超过2时,我们可以将链表分为第一个节点和后面所有的节点为一个节点,就转换成了两个节点的情况,使用递归实现如下:
/**
* 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;
if(!head.next.next){
//当节点数为2时
var temp = head.next;//保存返回的节点
head.next.next = head;
head.next = null;
}else{
var temp = reverseList(head.next);
head.next.next = head;
head.next = null;
}
return temp;
};
简洁版:
var reverseList = function(head) {
if(head == null ||head.next == null ) return head;
var temp = reverseList(head.next);
head.next.next = head;
head.next = null;
return temp;
};