问题1:链表翻转【leetcode206】
一个链表:a->b->c->d->e
反转后:e->d->c->b->a
输入:链表头指针
输出:反转后的链表头指针
方法 | 时间复杂度 | 空间复杂度 |
迭代法 | O(n) | O(1) |
递归法 | O(n) | O(n) |
# 定义链表
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# 翻转链表
#方法1
def backward1(head):
'''迭代法'''
if head is None:
print('Error: the nodelist is empty!')
pre = None
cur = head
while cur is not None:
newhead = cur
temp = cur.next
cur.next = pre
pre = cur
cur = temp
return newhead
#方法2
def backward2(head, newhead):
'''递归法'''
if head is None:
return
if head.next is None:
newhead = head
else:
newhead = backward2(head.next, newhead)
following = head.next
following.next = head
head.next = None
return newhead
# test
head = ListNode(1)
p1 = ListNode(3)
p2 = ListNode(5)
p3 = ListNode(7)
p4 = ListNode(9)
head.next = p1
p1.next = p2
p2.next = p3
p3.next = p4
res = backward2(head, None)
while res:
print(res.val)
res = res.next
问题2:链表两两翻转【leetcode24】
一个链表:a->b->c->d->e
每两个元素进行反转:b->a->d->c->e
输入:链表头指针
输出:反转后的链表头指针
# 定义链表
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# 两两反转链表
def swapPairs(head):
thead = ListNode(-1)
thead.next = head
c = thead
while c.next and c.next.next:
a, b=c.next, c.next.next
c.next, a.next = b, b.next
b.next = a
c = c.next.next
return thead.next
# test
head = ListNode(1)
p1 = ListNode(3)
p2 = ListNode(5)
p3 = ListNode(7)
p4 = ListNode(9)
head.next = p1
p1.next = p2
p2.next = p3
p3.next = p4
res = swapPairs(head)
while res:
print(res.val)
res = res.next