Leetcode刷题--移除链表元素

思路:

题解:


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {

    public ListNode removeElements(ListNode head, int val) {
        ListNode l0 = new ListNode(0);
        l0.next = head;
        ListNode prev = l0,curr = head;
        while(curr != null){
            if(curr.val == val){
                prev.next = curr.next;
                curr = curr.next;
            }else{
                prev = curr;
                curr = curr.next;
            }
        }
        return l0.next;
    }

}

猜你喜欢

转载自blog.csdn.net/qq_36428821/article/details/112972795