假设给定链表 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('没法删除!')
首先分配一个新结点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