1.10給定特定節點指針要求刪除該節點

只給單鏈表中要某節點處的指針的狀況下刪除該節點

題目描述:

假設給定鏈表 1->2->3->4->5->6->7 中指向第5個元素的指針,要求把結點5刪掉,刪除後鏈表變爲1->2->3->4->6->7node

思路分析:

1.若是這個結點是鏈表的最後一個結點,那麼沒法刪除這個結點。
2.若是這個結點不是鏈表的最後一個結點,能夠經過把其後繼結點的數據複製到當前結點中,而後刪除後繼結點的方法來實現。指針

代碼實現:

# -*-coding:utf-8-*- 
"""
@Author  : 圖南
@Software: PyCharm
@Time    : 2019/9/7 19:46
"""
class Node:
    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next


def printLink(head):
    if head is None or head.next is None:
        return
    cur = head.next
    while cur != None:
        print(cur.data, end=" ")
        cur = cur.next
    print()


def conLink(nums, n):
    nums = list(map(int, nums.split(' ')))
    n = int(n)
    if len(nums) == 0 or n == 0:
        return
    p = None
    head = Node()
    cur = head
    for i in range(1, len(nums)+1):
        node = Node(nums[i-1])
        cur.next = node
        cur = node
        if i == n:
            p = cur
    return head, p


def deleteP(p):
    if p.next is None:
        return False
    p.data = p.next.data
    p.next = p.next.next
    return True


if __name__ == '__main__':
    nums = input('鏈表:')
    n = input('節點數:')
    head, p = conLink(nums, n)
    print('刪除前:')
    printLink(head)
    f = deleteP(p)
    if f:
        print('刪除後:')
        printLink(head)
    else:
        print('沒法刪除!')

運行結果:


引伸:只給定單鏈表中某個結點p(非空結點),如何在p前面插入一個結點

解題思路:

首先分配一個新結點q,把結點q插入到結點p後,而後把p的數據域複製到結點q的數據域中,最後把結點p的數據域設置爲待插入的值。code

代碼實現:

# 給定節點p在p前插入一個節點
def insertP(head, p, num):
    node = Node()
    next = p.next
    p.next = node
    node.next = next
    node.data = p.data
    p.data = num

運行結果:

相關文章
相關標籤/搜索