如何在只给定单链表中某个结点的指针的情况下删除该结点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Chang_Shuang/article/details/86521851
"""
假设给定链表1->2->3->4->5->6->7中值向第5个元素的指针,要求把结点5删掉,删除后链表变为1->2->3->4->6->7.
"""


class LNode:
    def __init__(self):
        self.data = None
        self.next = None


def printList(head):
    cur = head.next
    while cur is not None:
        print(cur.data, end=' ')
        cur = cur.next


def RemoveNode(p):
    """
    方法功能:给定单链表中某个结点,删除该结点
    :param p: 链表中某结点
    :return: true:删除成功;false:删除失败
    """

    if p is None or p.next is None:
        return False
    p.data = p.next.data
    p.next = p.next.next
    return True


if __name__ == '__main__':
    i = 1
    head = LNode()
    tmp = None
    cur = head
    p = None
    # 构造链表
    while i < 8:
        tmp = LNode()
        tmp.data = i
        cur.next = tmp
        cur = tmp
        if i == 5:
            p = tmp
        i += 1
    print('删除结点' + str(p.data) + '前链表:')
    printList(head)
    result = RemoveNode(p)
    if result:
        print('\n删除该结点后链表:')
        printList(head)

运行结果如下:
删除结点5前链表:
1 2 3 4 5 6 7
删除该结点后链表:
1 2 3 4 6 7

猜你喜欢

转载自blog.csdn.net/Chang_Shuang/article/details/86521851