只给单链表中要某节点处的指针的情况下删除该节点
题目描述:
假设给定链表 1->2->3->4->5->6->7 中指向第5个元素的指针,要求把结点5删掉,删除后链表变为1->2->3->4->6->7
思路分析:
- 如果这个结点是链表的最后一个结点,那么无法删除这个结点。
如果这个结点不是链表的最后一个结点,可以通过把其后继结点的数据复制到当前结点中,然后删除后继结点的方法来实现。
代码实现:
# --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 = nextdef 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, pdef deleteP(p):
if p.next is None:
return False
p.data = p.next.data
p.next = p.next.next
return Trueif name == 'main':
nums = input('链表:')
n = input('节点数:')
head, p = conLink(nums, n)
print('删除前:')
printLink(head)
f = deleteP(p)
if f:
print('删除后:')
printLink(head)
else:
print('无法删除!')运行结果: