删除链表倒数第k个节点

class linkNode:
    def __init__(self, val, pnext):
        self.val = val;
        self.pnext = pnext

def removeLastK(head, n):
    if head == None:
        return head

    cur = head
    while cur:
        print(cur.val, end=" ")
        cur = cur.pnext
    print()

    first = head
    second = head

    #先走n步
    for i in range(n):
        if first:
            first = first.pnext
        else:
            break
    #走n步到None,倒数n就是head
    if not first:
        head = head.pnext
        cur = head
        while cur:
            print(cur.val, end=" ")
            cur = cur.pnext
        print()
        return head
    else:
        #再走一步, second是到数第n的前一个
        first = first.pnext
    while first:
        first = first.pnext
        second = second.pnext

    print(second.val)
    second.pnext = second.pnext.pnext

    cur = head
    while cur:
        print(cur.val, end=" ")
        cur = cur.pnext
    print()

    return head


n1 = linkNode(1, None)
n2 = linkNode(2, None)
n3 = linkNode(3, None)
n4 = linkNode(4, None)
n5 = linkNode(5, None)

n1.pnext = n2
n2.pnext = n3
n3.pnext = n4
n4.pnext = n5

removeLastK(n1, 5)

 

posted @ 2021-12-06 16:39  海228  阅读(22)  评论(0)    收藏  举报