leetcode with python:203. Remove Linked List Elements

题目:

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

给定一个linked list跟一个目标值(val),删除linked list所有值和val一样的node

一题算是简单的linked list操作

# Definition for singly-linked list.# class ListNode:#     def __init__(self, val=0, next=None):#         self.val = val#         self.next = nextclass Solution:    def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:        ll=ListNode()        ans=ll        while head:            if head.val != val:                ll.next=ListNode(head.val)                ll=ll.next            head=head.next        return ans.next

先开一个新head来存放新的linked list(ans)
之后开始走访linked list,值不是val的node全部依序接到ans后面
这样一个没有val值的新linked list就完成了
之后回传ans.next即可
最后执行时间74ms(faster than 88.94%)

除了这个解法以外,我还写了个递迴解,如下

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

一旦head非None且值等于val就无视跳下一个
跳完若head非None的话,head.next也用同样的方式递迴下去找
next找好后就回传head
最后回传的head就是新linked list的头了
最后执行时间64ms(faster than 98.50%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章