题目
Given a singly-linked list, reverse the list. This can be done iteratively or recursively. Can you get both solutions?
Example:
Input: 4 -> 3 -> 2 -> 1 -> 0 -> NULL
Output: 0 -> 1 -> 2 -> 3 -> 4 -> NULL
要求做出递归法和迭代法2种写法。
分析
递归法:
将第二个元素开始的尾部链表递归反转,然后拼到第一个元素上去。接下来需要额外做一次迭代,找到新链表的头指针以便返回。这里暂时没想到更有效的解法,可能不是最优的。
迭代法:
用2个指针,一个 created 表示新创建的结果链表的头指针,另一个 remaining 表示剩余可用的节点的指针。从原来的链表上依次拆除元素,添加到新链表,添加的时候,顺便调整指针以便反转之。这里,链表调整各节点指向关系的代码不算难,但是有点饶人,需要多加练习,以增加熟练度,并做到思路清楚。
时间复杂度 O(n).
代码
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