File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed
Leetcode/leetcodeTags/LinkedList Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change 1+ package LinkedList ;
2+
3+ public class RemoveLinkedListElement203 {
4+
5+ public class ListNode {
6+ int val ;
7+ ListNode next ;
8+
9+ ListNode () {
10+ }
11+
12+ ListNode (int val ) {
13+ this .val = val ;
14+ }
15+
16+ ListNode (int val , ListNode next ) {
17+ this .val = val ;
18+ this .next = next ;
19+ }
20+ }
21+
22+ // O(N) time, O(1) space
23+ public ListNode removeElements (ListNode head , int val ) {
24+
25+ if (head == null )
26+ if (head == null )
27+ return null ;
28+
29+ ListNode dummy = new ListNode (-1 );
30+ dummy .next = head ;
31+ ListNode tail = dummy ;
32+
33+ while (head != null ) {
34+ if (head .val == val ) {
35+ ListNode temp = head .next ;
36+ tail .next = temp ;
37+ head = temp ;
38+ } else {
39+ head = head .next ;
40+ tail = tail .next ;
41+ }
42+ }
43+
44+ return dummy .next ;
45+ }
46+
47+ // recursive approach
48+ public ListNode removeElementsRecursive (ListNode head , int val ) {
49+
50+ if (head == null )
51+ return null ;
52+
53+ head .next = removeElementsRecursive (head .next , val );
54+
55+ // can also write it using ternary operator
56+ if (head .val == val ) {
57+ return head .next ;
58+ } else
59+ return head ;
60+ }
61+ }
You can’t perform that action at this time.
0 commit comments