203.Remove Linked List Elements(刪除鏈表中值爲X的結點)

題目: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

思路:新建一個val=-1的頭節點,從head結點開始,判斷值是否與目標值相等,不相等就加在新建結點後

代碼:

public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        
        ListNode cur = new ListNode(-1);
        ListNode res = cur ;
        
        while(head!=null){
            if(head.val!=val){
                cur.next = head;
                cur = cur.next;
            }
            head = head.next;
        }
        
        cur.next = null;
        return res.next ;
 
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章