第六版Cracking the Coding Interview题目2.3,题目如下:
Delete Middle Node: Implement an algorithm to delete a node in the middle (i.e., any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node.
EXAMPLE
Input: the node c from the linked list a - >b- >c - >d - >e- >f
Result: nothing is returned, but the new linked list looks like a - >b- >d - >e- >f
题目的要求为得到单链表中间的一个节点,在不能访问链表头的情况下删除这个节点。那么需要做的是将下一个节点的数据拷贝到当前节点,然后删除下一个节点。
def deleteMiddleNode(node):
if node is None or node.getNext() is None:
raise ValueError('input node cannot be None or the last node')
nextNode = node.getNext()
node.setItem(nextNode.getItem())
node.setNext(nextNode.getNext())
del nextNode
在手机上阅读或分享本文请扫描以下二维码:
Comments