-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremoveLinkedListElements.java
More file actions
53 lines (46 loc) · 1.69 KB
/
removeLinkedListElements.java
File metadata and controls
53 lines (46 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
*/
/**
* 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) {
// assign current Node to curNode.
ListNode curNode = head;
// assign prev Node to null.
ListNode preNode = null;
// Check the head node it self equal to value.
// If so assign the head to next node (which means deleting the current node).
while(curNode != null && curNode.val == val){
head = curNode.next;
curNode = head;
}
while (curNode != null) {
// if curNode val is not equals to val then assign next node to current node and current node to prev node.
if(curNode.val != val){
preNode = curNode;
curNode = curNode.next;
//System.out.println(curNode.val+"-------"+preNode.val);
}
// if curNode val is equals to val then assign current node next to prevoius node next. // means skipping the current node value.
//assign the current node to previous node next.
else {
preNode.next = curNode.next;
curNode = preNode.next;
//System.out.println("-----"+curNode.val+"-------"+preNode.val);
}
}
return head;
}
}