LeetCode(52)-Remove Linked List Elements
題目:
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;
}
}