反轉鏈表

題目

Given a singly-linked list, reverse the list. This can be done iteratively or recursively. Can you get both solutions?node

Example:
Input: 4 -> 3 -> 2 -> 1 -> 0 -> NULL
Output: 0 -> 1 -> 2 -> 3 -> 4 -> NULL指針

要求作出遞歸法和迭代法2種寫法。code

分析

遞歸法:
將第二個元素開始的尾部鏈表遞歸反轉,而後拼到第一個元素上去。接下來須要額外作一次迭代,找到新鏈表的頭指針以便返回。這裏暫時沒想到更有效的解法,可能不是最優的。遞歸

迭代法:
用2個指針,一個 created 表示新建立的結果鏈表的頭指針,另外一個 remaining 表示剩餘可用的節點的指針。從原來的鏈表上依次拆除元素,添加到新鏈表,添加的時候,順便調整指針以便反轉之。這裏,鏈表調整各節點指向關係的代碼不算難,可是有點饒人,須要多加練習,以增長熟練度,並作到思路清楚。rem

時間複雜度 O(n).get

代碼

class ListNode(object):
  def __init__(self, x):
    self.val = x
    self.next = None
  
  # Function to print the list
  def printList(self):
    node = self
    output = '' 
    while node != None:
      output += str(node.val)
      output += " "
      node = node.next
    print(output)

  # Iterative Solution
  def reverseIteratively(self, head):
    created = None
    remaining = head

    while remaining:
      new_remaining = remaining.next
      remaining.next = created
      created = remaining
      remaining = new_remaining
    
    return created

  # Recursive Solution      
  def reverseRecursively(self, head):
    if head.next:
      tail = self.reverseRecursively(head.next)
      p = tail
      while p.next:
        p = p.next
      p.next = head
      head.next = None
      return tail
    else:
      return head

# Test Program
# Initialize the test list: 
testHead = ListNode(4)
node1 = ListNode(3)
testHead.next = node1
node2 = ListNode(2)
node1.next = node2
node3 = ListNode(1)
node2.next = node3
testTail = ListNode(0)
node3.next = testTail

print("Initial list: ")
testHead.printList()
# 4 3 2 1 0
testHead.reverseIteratively(testHead)
# testHead.reverseRecursively(testHead)
print("List after reversal: ")
testTail.printList()
# 0 1 2 3 4
相關文章
相關標籤/搜索