您当前的位置: 首页 > 

IT之一小佬

暂无认证

  • 0浏览

    0关注

    1192博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

删除中间节点

IT之一小佬 发布时间:2021-04-18 10:59:07 ,浏览量:0

删除中间节点

实现一种算法,删除单向链表中间的某个节点(即不是第一个或最后一个节点),假定你只能访问该节点。

示例:

输入:单向链表a->b->c->d->e->f中的节点c
结果:不返回任何数据,但该链表变为a->b->d->e->f

示例代码:

# Definition for singly-linked list.
class LinkNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution(object):
    #  create a linklist
    def creat_linklist(self, li):
        if not li:
            print('This is an empty list')
            return
        head = p = LinkNode(li[0])

        for i in li[1:]:
            p.next = LinkNode(i)
            p = p.next
        return head

    def print_linklist(self, head):
        if not head:
            print('This is an empty list')
            return
        while head:
            print(head.val, end="->")
            head = head.next
        print('None')

    def del_node(self, head, node):
        if not head:
            print('This is an empty list')
            return
        while head:
            if head.val == node:
                head.val = head.next.val
                head.next = head.next.next
            head = head.next


#  test
li = ['a', 'b', 'c', 'd', 'e', 'f']
obj = Solution()
head = obj.creat_linklist(li)
obj.print_linklist(head)
obj.del_node(head, 'c')
obj.print_linklist(head)

运行结果:

关注
打赏
1665675218
查看更多评论
立即登录/注册

微信扫码登录

0.0416s