203. Remove Linked List Elements

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

这道题维持两个可以移动的指针prev, curt. 分别初始化为prev = dummy, curt = head. 所以一开始就有prev.next = curt. 然后用curt遍历链表,遇到curt.val == val的时候,就让prev.next = curt.next来删掉该节点;没有遇到就直接前移prev. 两种情况都会前移curt = curt.next来继续遍历。最后返回固定节点dummy.next来返回结果。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode prev = dummy;
        ListNode curt = head;
        while (curt != null){
            if (curt.val == val){
                prev.next = curt.next;
            } else {
                prev = curt;
            }
            curt = curt.next;
        }
        return dummy.next;
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/f65ee70a98ef
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞