Problem:
Remove all elements from a linked list of integers that have value val.
Explanation:
删除链表中所有指定值的结点。
My Thinking:
遍历结点并判断即可。
My Solution:
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode fakehead=new ListNode(-1);
fakehead.next=head;
ListNode returnhead=fakehead;
while(fakehead!=null && fakehead.next!=null){
if(fakehead.next.val==val){
fakehead.next=fakehead.next.next;//这里不需要向后移,因为删除结点相当于向后移了
}else{
fakehead=fakehead.next;
}
}
return returnhead.next;
}
}
Optimum Thinking:
使用递归
Optimum Solution:
class Solution {
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;
}
}