python 实现链表反转操作

代码如下:

class ListNode():
    def __init__(self,x):
        self.val =x 
        self.next = None
        
def printNode(head):
    curr=head
    while curr is not None:
        print(curr.val,end=' -> ')
        curr=curr.next
    print("None")

def reserse(head):
    if head is None:
        return
    temp = head.next
    prev = None
    curr = head
    while curr is not None:
        temp = curr.next
        curr.next = prev
        prev = curr
        curr = temp
    return prev


def reserseBetween(head, m, n):
    def reverse(root, prep, k):
        curr = root
        prev = None
        temp = None
        while curr is not None and k>0:
            temp = curr.next
            curr.next = prev
            prev = curr
            curr= temp
            k -=1
        root.next= temp
        prep.next= prev
        return prev
    dummy = ListNode(-1)
    dummy.next = head
    k = 0 
    p = dummy
    start = None
    while p is not None:
        if k==m:
            start = p
        if k==n+1:
            reverse(start.next, start, n-m+1)
            return dummy.next
        k +=1
        p=p.next

def n_reverse(head, start_pos, n, repeat=True):
    def reverse(root, prep, k):
        curr = root
        prev = None
        temp = None
        while curr is not None and k>0:
            temp = curr.next
            curr.next = prev
            prev = curr
            curr= temp
            k -=1
        root.next= temp
        prep.next= prev
        return root
    if start_pos <1:
        raise ValueError("Start position should be greater than 0")
    dummy = ListNode(-1)
    dummy.next = head
    k = 0 
    p = dummy
    start = None
    while p is not None:
        if k == start_pos:
            start = p
        if k > 1 and k%n==1:
            start = reverse(start.next, start, n)
            if not repeat:
                return dummy.next
        k +=1
        p=p.next
    return dummy.next




if __name__ == '__main__':
    n=10
    l0=ListNode(0)
    for i in range(1,n):
        exec(f"l{i}=ListNode({i})")
        exec(f"l{i-1}.next=l{i}")

    printNode(l0)
    ll=reserseBetween(l0, 1,3)
    printNode(ll)
    ll=n_reverse(ll, 1, 3,False)
    printNode(ll)
    ll = n_reverse(ll, 1, 3)
    printNode(ll)
    ll=reserse(ll)
    printNode(ll)
'''
0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> None
0 -> 3 -> 2 -> 1 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> None
0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> None
0 -> 3 -> 2 -> 1 -> 6 -> 5 -> 4 -> 9 -> 8 -> 7 -> None
7 -> 8 -> 9 -> 4 -> 5 -> 6 -> 1 -> 2 -> 3 -> 0 -> None
'''


©️2020 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值