206. Reverse Linked List
https://leetcode.com/problems/reverse-linked-list/
js
/**
* 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) {
return head
}
var current = head.next
head.next = null
while (current) {
let next = current.next
current.next = head
head = current
current = next
}
return head
}
js
/**
* 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 || !head.next) {
return head
}
var next = head.next
var reverse = reverseList(next)
next.next = head
head.next = null
return reverse
}
py
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return head
current = head.next
head.next = None
while current:
nxt = current.next
current.next = head
head, current = current, nxt
return head
py
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
nxt, reverse = head.next, self.reverseList(head.next)
nxt.next, head.next = head, None
return reverse