【python数据结构】链表翻转问题合集

问题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

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值