Leetcode
Leetcode copied to clipboard
206. 反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。 示例 1: 输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
示例 2: 输入:head = [1,2] 输出:[2,1]
示例 3: 输入:head = [] 输出:[] 提示:
链表中节点的数目范围是 [0, 5000] -5000 <= Node.val <= 5000
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
206. 反转链表
迭代的方法
pre = null
cur = head
(指向空节点)
pre cur(指向当前的头节点)
null 1 -> 2 -> 3 -> 4 -> 5 -> null
pre = null
cur = head
当当前节点不为空的时候
pre cur next
null <- 1 2 -> 3 -> 4 -> 5 -> null
next = current.next
cur.next = pre
cur
pre next
null <- 1 2 -> 3 -> 4 -> 5 -> null
pre = cur
cur = next
next = current.next
cur.next = pre
直到cur节点为空 return pre
*/
var reverseList = function(head) {
let pre = null, cur = head, next
// 判断当前指针
while(cur) {
next = cur.next
cur.next = pre
pre = cur
cur = next
}
return pre
};
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
206. 反转链表
递归的方法
*/
var reverseList = function(head) {
if(head === null || head.next === null) {
return head
}
const node = reverseList(head.next)
head.next.next = head
head.next = null
return node
};