力扣203題(移除連結串列元素)
阿新 • • 發佈:2021-10-10
203、移除連結串列元素
具體實現:
如果頭結點是要刪除的元素選擇兩種方式
1、直接使用原來的連結串列進行刪除操作
2、設定一個虛擬頭結點再進行刪除操作
程式碼:
1、不設定虛擬結點
class Solution { public ListNode removeElements(ListNode head, int val) { if (head == null){ return head; } ListNode dummy = new ListNode(-1, head); ListNode pre= dummy; ListNode cur = head; while (cur != null) { if (cur.val == val){ pre.next = cur.next; } else{ pre = cur; } cur = cur.next; } return dummy.next; } }
class Solution {public ListNode removeElements(ListNode head, int val) { while (head != null && head.val == val){//如果頭結點是要刪除的值,就讓頭結點指向下一個節點 head = head.next; } if (head == null){ return head; } ListNode pre = head; ListNode cur = head.next;while (cur != null) { if (cur.val == val){ pre.next = cur.next; } else{ pre = cur; } cur = cur.next; } return head; } }
2、設定虛擬頭結點