Try   HackMD

203. Remove Linked List Elements(E)

important: 8
tags: Linked List
tags: Amazon FB Apple Google Bloomberg Microsoft

Leetcode 203

Q: Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

:bulb: Hint: Use "Dummy Node" to be the another linked list head.

/**
 * 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; }
 * }
 */

1. Sentinel Node

class Solution { public ListNode removeElements(ListNode head, int val) { //Use dummy node to delete the val nodes ListNode dummy=new ListNode(0); dummy.next=head; ListNode prev=dummy; ListNode cur=head; while(cur!=null){ if(cur.val==val){ prev.next=cur.next; cur=cur.next; } else{ prev=cur; cur=cur.next; } } return dummy.next; } }

Time complexity :O(N) Space complexity :O(1)