反转链表
https://leetcode.cn/problems/reverse-linked-list/ (opens new window)
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre = None
cur = head
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}
*/
var reverseList = function(head) {
let cur = head
let pre = null
while(cur != null){
const t = cur.next
cur.next = pre
pre = cur
cur = t
}
return pre
};
/**
* @param {ListNode} head
* @return {ListNode}
*/
// 参考leetcode cn 官网 解答
var reverseList = function(head) {
if(head == null || head.next == null) return head
let newHead = reverseList(head.next)
// 前一个节点是有后一个节点的信息,
// 然后前一个节点->后一个节点, 转变成, 后一个节点 -> 前一个节点
head.next.next = head
// 前一个节点的next 需要变成 null
head.next = null
return newHead
};