# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverse(self, head):
"""
input: ListNode head
return: ListNode
"""
# write your solution here
if head == None:
return head
prev = None
curr = head
while (curr != None and curr.next != None):
### We break out the loop when we have current as the last element. All elements till then has the same operation. The last element needs extra care so we deal with it outside the loop.
### action in every round of loop
# keep control of the next node
after = curr.next
# swap curr to point to prev
curr.next = prev
# update curr, prev and next so we proceed to the next group of node
prev = curr
curr = after
after = after.next
# break out the loop. Now we have curr at the last node! But it has not been reversed yet.
curr.next = prev
head = curr
return head
lost base case.
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.