# 203 Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
題目解析:
如上述範例,給一個linked list 及一個int val,若lined list裡有與val相同的值就刪掉。
實際上linked list並沒有刪掉,只是node的next不要指向val node即可。改指向下一個node即可
程式碼:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null){
return head;
}
ListNode slow = null;
ListNode fast = head;
// ListNode temp = null;
while(fast != null){
// if(fast.next != null){
// System.out.println("fast.val = "+ fast.val + " , fast.next = " + fast.next + " , fast.next.val = " + fast.next.val);
// }else{
// System.out.println("fast.val = "+ fast.val + " , fast.next = " + fast.next );
// }
if(fast.val == val){
if(slow != null){
slow.next = fast.next;
}else{
head = fast.next;
}
}else{
slow = fast;
}
fast = fast.next;
}
// //print
// temp = head;
// while(temp != null){
// System.out.println("t = "+ temp.val );
// temp = temp.next;
// }
return head;
}
}
Last updated
Was this helpful?