🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
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 ~~~ ``` /** * 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) { while(head != null && head.val == val){ ListNode delNode = head; head = head.next; delNode.next = null; } if(head == null) return head; ListNode prev = head; while(prev.next != null){ if(prev.next.val == val) { ListNode delNode = prev.next; prev.next = delNode.next; delNode.next = null; } else prev = prev.next; } return head; } } ``` ``` class Solution2 { public ListNode removeElements(ListNode head, int val) { while(head != null && head.val == val) head = head.next; if(head == null) return head; ListNode prev = head; while(prev.next != null){ if(prev.next.val == val) prev.next = prev.next.next; else prev = prev.next; } return head; } } ``` ``` class Solution3 { public ListNode removeElements(ListNode head, int val) { ListNode dummyHead = new ListNode(-1); dummyHead.next = head; ListNode prev = dummyHead; while(prev.next != null){ if(prev.next.val == val) prev.next = prev.next.next; else prev = prev.next; } return dummyHead.next; } } ``` ``` class Solution4 { public ListNode removeElements(ListNode head, int val) { if(head == null) return head; head.next = removeElements(head.next, val); return head.val == val ? head.next : head; } } ```