Delete Node in the Middle of Singly Linked List

Question

Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node.

Example Given 1->2->3->4, and node 3. return 1->2->4

Thoughts

In the middle of singly linked list,没有parent,一个一个将value换成后面一个,并将最后的tail去掉

Analysis

Solution

"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""
class Solution:
    # @param node: the node in the list should be deleted
    # @return: nothing
    def deleteNode(self, node):
        # write your code here
        if not node.next:
            return
        while node.next.next:
            node.val = node.next.val
            node = node.next

        node.val = node.next.val
        node.next = None