删除链表中等于给定值 val 的所有节点。

    示例:

    输入: 1->2->6->3->4->5->6, val = 6
    输出: 1->2->3->4->5
    https://leetcode-cn.com/problems/remove-linked-list-elements/

    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. * int val;
    5. * ListNode next;
    6. * ListNode(int x) { val = x; }
    7. * }
    8. */
    9. class Solution {
    10. public ListNode removeElements(ListNode head, int val) {
    11. ListNode node=head;
    12. while(node!=null&&node.next!=null){
    13. if(node.next.val==val){
    14. node.next=node.next.next;
    15. }else{
    16. node=node.next;
    17. }
    18. }
    19. if(head!=null&&head.val==val) {
    20. head=head.next;
    21. }
    22. return head;
    23. }
    24. }
    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. * int val;
    5. * ListNode next;
    6. * ListNode(int x) { val = x; }
    7. * }
    8. */
    9. class Solution {
    10. public ListNode removeElements(ListNode head, int val) {
    11. if(head==null){
    12. return null;
    13. }
    14. if(head.val==val&&head.next==null){
    15. return null;
    16. }
    17. ListNode node;
    18. node=head;
    19. while(node!=null&&node.next!=null){
    20. if(node.next.val==val){
    21. node.next=node.next.next;
    22. }else{
    23. node=node.next;
    24. }
    25. }
    26. if(head.val==val){
    27. head=head.next;
    28. }
    29. return head;
    30. }
    31. }