Leetcode解题-Reverse Linked List

描述

Reverse a singly linked list.

分析

简单题,翻转单链表。时间O(n),空间O(1)

代码

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 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
"""

last = None
while head:
next = head.next
head.next = last
last = head
head = next
return last

热评文章