Problem:
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
Analysis:
利用一个helper节点作为头节点这个技巧很棒,答案中判断p.next!=null则将这个节点删除,后面的节点还需要再次考察,所以不用p=p.next。
Answer:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode helper = new ListNode(0);
helper.next=head;
ListNode p = helper;
while(p.next!=null){
if(p.next.val==val) p.next=p.next.next;
else p=p.next;
}
return helper.next;
}
}
看到大家的解法中有用俩个指针的,但是显然没有上个解法好
连个指针解法:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode p = dummy;
ListNode q = head;
while(q!=null) {
if(q.val == val) {
p.next = q.next;
} else {
p = p.next;
}
q = q.next;
}
return dummy.next;
}
}