zoukankan      html  css  js  c++  java
  • 删除链表中的节点

    请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。

    现有一个链表 -- head = [4,5,1,9],它可以表示为:

    示例 1:

    输入: head = [4,5,1,9], node = 5
    输出: [4,1,9]
    解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
    示例 2:

    输入: head = [4,5,1,9], node = 1
    输出: [4,5,9]
    解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.

    说明:

    链表至少包含两个节点。
    链表中所有节点的值都是唯一的。
    给定的节点为非末尾节点并且一定是链表中的一个有效节点。
    不要从你的函数中返回任何结果。

    # 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.
    """

    解答:

    import re
    class Solution(object):
    def __init__(self):
    pass
    #重新建新列表
    def deleteNode(self,xlist,node):
    output = []
    if node == None:
    input("请输入要删除的结点: ")
    else:
    if node == xlist[-1]:
    print("不能删除未尾结点:")
    exit(0)
    if node not in xlist:
    print("找不到您要删除的结点:")
    exit(0)
    else:
    xlist = self.Str2Int(xlist)
    xxlist = list(set(xlist))#去重复
    xxlist.sort(key = xlist.index)#按原样输出
    for i in xxlist:
    if i!= int(node):
    output.append(i)
    return output
    #转化为列表整数
    def Str2Int(self,str):
    xlist = str.split(",")
    xlist = [int(xlist[i]) for i in range(len(xlist))]
    return xlist

    if __name__ == '__main__':
    x = input("请输入链表结点,数字与半角逗号分隔 ,结点不能少于2个 ")
    if not re.search('^[0-9,]+$', x):
    print('格式错误 ')
    exit(0)
    s = Solution()
    n = input("请输入要删除的结点: ")
    if not re.search('^[0-9]+$', n):
    print('格式错误')
    exit(0)
    r = s.deleteNode(x,n)
    print(r)
  • 相关阅读:
    CodeForces 706C Hard problem
    CodeForces 706A Beru-taxi
    CodeForces 706B Interesting drink
    CodeForces 706E Working routine
    CodeForces 706D Vasiliy's Multiset
    CodeForces 703B Mishka and trip
    CodeForces 703C Chris and Road
    POJ 1835 宇航员
    HDU 4907 Task schedule
    HDU 4911 Inversion
  • 原文地址:https://www.cnblogs.com/zbligang/p/10413486.html
Copyright © 2011-2022 走看看