面试题 02.03. 删除中间节点
原始题目链接:https://leetcode-cn.com/problems/delete-middle-node-lcci/
实现一种算法,删除单向链表中间的某个节点(即不是第一个或最后一个节点),假定你只能访问该节点。
示例:
输入:单向链表a->b->c->d->e->f中的节点c
结果:不返回任何数据,但该链表变为a->b->d->e->f
解题思路:
这道题只知道要删除的链表的节点,不知道表头,删除节点需要知道这个节点的前驱节点,但是本体找不到,所以使用移动覆盖节点值的方法解题,将要删除节点的后面的节点值依次左移,再讲最后一个节点断开即可,具体实现开代码。
代码实现:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
cur = node
while cur.next and cur.next.next:
cur.val = cur.next.val
cur = cur.next
cur.val = cur.next.val
cur.next = None