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
My code:
public ListNode removeElements(ListNode head, int val) {
ListNode fakeHead = new ListNode(-1);
fakeHead.next = head;
ListNode cur = head, pre = fakeHead;
while(cur!=null){
if (cur.val ==val) {
pre.next = cur.next;
}
else{
pre = pre.next;
}
cur = cur.next;
}
return fakeHead.next;
}
总结:思路没问题,看了下答案。注意 fakehead的设置。何时改变原有的linked list,何时不改变,是个问题。
递归方法:
public ListNode removeElements(ListNode head, int val) {
if(head == null) return null;
head.next = removeElements(head.next, val);
return head.val==val?head.next:head;
}
总结:简单地简直丧心病狂!