LeetCode:Remove Linked List Elements

Posted walker lee

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:Remove Linked List Elements相关的知识,希望对你有一定的参考价值。

Remove Linked List Elements


Total Accepted: 65900 Total Submissions: 226939 Difficulty: Easy

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

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Hide Tags
 Linked List





















思路:

链表的题只要在原链表中加一个“伪”头结点,一切都变得简单了。


java code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode p = dummy;
        while(p.next != null) {
            if(p.next.val == val)
                p.next = p.next.next;
            else 
                p = p.next;
        }
        return dummy.next;
    }
}


以上是关于LeetCode:Remove Linked List Elements的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] Remove Element 分析

206. Reverse Linked List

234. Palindrome Linked List

Reverse Linked List | & ||

LeetCode Remove Element

LeetCode Remove Duplicate Letters