算法笔记: 力扣#206 反转链表

问题描述


解法


分析

Python 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class :
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
prev = None
cur = head
while cur:
temp = cur.next
cur.next = prev
prev = cur
cur = temp
return prev

Java 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode cur = head;
while(cur != null){
ListNode temp = cur.next;
cur.next = prev;
prev = cur;
cur = temp;
}
return prev;
}
}

时间复杂度

O(n).

空间复杂度

O(1).

链接


206. Reverse Linked List
206. 反转链表
(English version) Algorithm Notes: Leetcode#206 Reverse Linked List