【leetcode】203:移除链表元素

题目如下所示:

 

 这个题目也就是你一遇到一个node符合要求,你就可以将其删除。是一个比较简单的基础题目,用于熟悉链表当中的最基本操作。我们可以使用如下的方法,也就是暴力法,遍历整个linked list,然后将所有的nodes保存到一个list里面,对不符合要求的values进行排除,然后再重新建立一个新的linked list,将符合要求的values放置进去。但是这样的话,虽然时间复杂度为o(n),但是空间复杂度却有点大,我们先来看看这个方法的代码实现:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        ls=[]
        while head:
            ls.append(head)
            head=head.next
        new_ls=[]
        for i in ls:
            if i.val==val:
                pass
            else:
                new_ls.append(i.val)
        ret=ListNode(0)
        cur=ret
        for i in new_ls:
            ret.next=ListNode(i)
            ret=ret.next
        return cur.next

方法二:

使用dummy vaiable

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        dummy = ListNode()
        dummy.next = head
        p = dummy
        while p is not None:
            # 向前探一个节点检查是否等于val
            if p.next and p.next.val == val:
                # 跳过 p.next 节点
                p.next = p.next.next 
            else:
                p = p.next
        return dummy.next

同样的方法,不同的变量:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        cur=ListNode(0)
        cur.next=head
        node=cur
        while cur:
            if cur.next and cur.next.val==val:
                cur.next=cur.next.next
            else:
                cur=cur.next
        return node.next

我们使用这个方法,所需要用到的判断永远是使用cur.next进行判断,有可能漏掉第一个node,因此我们需要设定一个cur在head的前面。对head的第一个node进行判断

 

posted @ 2021-08-28 09:26  Geeksongs  阅读(37)  评论(0编辑  收藏  举报

Coded by Geeksongs on Linux

All rights reserved, no one is allowed to pirate or use the document for other purposes.