资讯专栏INFORMATION COLUMN

[LintCode] Remove Linked List Elements

huayeluoliuhen / 2204人阅读

Problem

Remove all elements from a linked list of integers that have value val.

Example

Given 1->2->3->3->4->5->3, val = 3, you should return the list as 1->2->4->5

Solution
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        // Write your code here
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
        while (head.next != null) {
            if (head.next.val == val) {
                head.next = head.next.next;
            }
        else {
            head = head.next;
            }
        }    
        return dummy.next;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65432.html

相关文章

  • [LeetCode/LintCode] Remove Nth Node From End of L

    Problem Given a linked list, remove the nth node from the end of list and return its head. Example Given linked list: 1->2->3->4->5->null, and n = 2. After removing the second node from the end, the l...

    Jaden 评论0 收藏0
  • [LintCode] Remove Duplicates form Sorted List I &a

    摘要:和上一道题不同的地方就是,需要用双指针操作,且最后要返回,以防止结点即的情况返回错误的结果。令,用进行查重操作,是的前结点。当和等值的时候,后移至第一个不等值的点,用指向新的即可。 Remove Duplicates form Sorted List I Problem Given a sorted linked list, delete all duplicates such tha...

    int64 评论0 收藏0
  • [LintCode/LeetCode] LRU Cache

    摘要:方法继承了的很多方法,本身的方法有对运行速度影响不大,随意设定是默认值,为浮点数为,与意思相同最近过的 Problem Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. ge...

    walterrwu 评论0 收藏0
  • 148. Sort List

    摘要:题目分析一看到问题,而且时间复杂度要求又是,很自然地就会想到数组时,如下这道题要求是,所以在上面的基础上还要进行一些额外操作找到的中点,使用快慢指针法。需要注意的是,找到中点后要把链表分成两段,即两个链表。这部分代码应该近似于这道题的答案。 Sort a linked list in O(n log n) time using constant space complexity. 题...

    anquan 评论0 收藏0
  • [LintCode/LeetCode] Convert Sorted List to Balance

    摘要:当链表为空时,中出现大于,返回。然后计算中点,以为界分别递归构建左右子树。顺序是,左子树根结点右子树。由于根节点是直接取构建,当前的已经被取用。所以在下一次递归构建右子树之前,要让指向。最后将和左右子树相连,返回。 Problem Given a singly linked list where elements are sorted in ascending order, conve...

    Michael_Ding 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<