题目链接
https://leetcode.com/problems/delete-node-in-a-linked-list/
题目原文
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is
1 -> 2 -> 3 -> 4
and you are given the third node with value3
, the linked list should become1 -> 2 -> 4
after calling your function.
题目翻译
写个函数删除一个单链表中的一个节点(非尾节点),该函数的参数是要删除的节点。
比如一个链表是 1 -> 2 -> 3 -> 4
, 给你一个值为3的节点,调用你的函数后链表变成 1 -> 2 -> 4
。
思路方法
这是一个非常简单的单链表的题,稍微拐了一点弯。一般删除一个节点是通过上一个节点来操作,现在只给了当前节点,那么只能将后一节点的值赋给当前节点,将后一节点删掉,则相当于删掉了“当前节点”。
代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next
说明
然而这个题还是有点争议的,有人认为删除意味着释放该空间,那么交换值不合题意,这个节点就没法删掉了。。。
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51398604