203. Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Example:
Example:
Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5
移除链表中的元素
从链表中移除与 val 相等的节点
递归方法:
public class RemoveLinkedListElements { public ListNode removeElements(ListNode head, int val) { return dfs(head, val); } public ListNode dfs(ListNode head, int val) { if (head == null) return null; if (head.next != null && head.next.val == val) { head.next = head.next.next; dfs(head, val); } else { dfs(head.next, val); } return (head.val == val) ? head.next : head; } }
非递归方法:
public class RemoveLinkedListElements { public ListNode removeElements(ListNode head, int val) { ListNode headListNode = new ListNode(0); headListNode.next = head; ListNode tempListNode = headListNode; while (tempListNode.next != null) { if (tempListNode.next.val == val) { tempListNode.next = tempListNode.next.next; }else { tempListNode = tempListNode.next; } } return headListNode.next; } }