題目
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
Iteration 遍歷執行
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode fakeHead = new ListNode(-1);
fakeHead.next = head;
ListNode pre = fakeHead;
while (head != null) {
if (head.val == val) {
pre.next = head.next;
} else {
pre = head;
}
head = head.next;
}
return fakeHead.next;
}
}
Recursive遞歸執行
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
// exit condition
if (head == null) return null;
// recursive from tail to head.
head.next = removeElements(head.next, val);
return head.val == val ? head.next : head;
}
}