定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
思路:(1).双指针 (2).递归
双指针:
/** 2020.5.2 11:09
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
/** 2020.5.2 11:09
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
let result = null; //结果链表
let tempNode = null; //临时链表,用于存放除链表头部以外的链表部分
let node = head; //原链表
while(node!==null){
tempNode = node.next; //接收原链表后部分
node.next = result; //将结果链表接在原链表头后
result = node; //将原链表头加结果链表赋值给结果链表
node = tempNode; //将原链表后部分返回原链表
}
return result;
};
递归:
/** 2020.5.2 11:09
* 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{
let result = reverseList(head.next);
head.next.next = head;
head.next = null;
return result;
}
};