# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None:
return head
prev = None # previous initialization as None so that the logic applies to head as well
curr = head
while (curr != None and curr.next != None): # curr != None is edge case, curr.next != None is stop condition
after = curr.next
curr.next = prev # reset the link
prev = curr # move pointer
curr = after
after = after.next
curr.next = prev
return curr
解法可能不是很完美。注意链表的分割。以及最后一步 curr.next = prev 易出错。
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.