给定单链表的头节点 head
,请反转链表,并返回反转后的链表的头节点。
注意:本题与主站 206 题相同: https://leetcode-cn.com/problems/reverse-linked-list/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre, p = None, head
while p:
q = p.next
p.next = pre
pre = p
p = q
return pre
迭代版本:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null, p = head;
while (p != null) {
ListNode q = p.next;
p.next = pre;
pre = p;
p = q;
}
return pre;
}
}
递归版本:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode res = reverseList(head.next);
head.next.next = head;
head.next = null;
return res;
}
}
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function (head) {
let node = head;
let pre = null;
while (node) {
let cur = node;
node = cur.next;
cur.next = pre;
pre = cur;
}
return pre;
};
func reverseList(head *ListNode) *ListNode {
if head == nil ||head.Next == nil {
return head
}
dummyHead := &ListNode{}
cur := head
for cur != nil {
tmp := cur.Next
cur.Next = dummyHead.Next
dummyHead.Next = cur
cur = tmp
}
return dummyHead.Next
}