题目:
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
思路:
- 题意:有序列表里面去掉给定的元素
- 遍历发现相同的,就去掉,prev.next != null,发现了prev.next = prev.next.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) {
if(head == null){
return null;
}
while(head.val == val){
head = head.next;
if(head == null){
return null;
}
}
ListNode prev = head;
while(prev.next != null){
while(prev.next.val == val){
prev.next = prev.next.next;
if(prev.next == null){
return head;
}
}
prev = prev.next;
}
return head;
}
}