203. Remove Linked List Elements & 237. Delete Node in a Linked List

在单链表中删除与target相等的值

/**
 * 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) {
        ListNode cur=new ListNode(0);
        cur.next=head;
        ListNode res= cur;
        while(res.next!=null){//循环比较下一元素,直至无重复值在跳至下一节点
            if(res.next.val == val)
                res.next=res.next.next;
            else
                res=res.next;
        }
        return cur.next;
    }
}

输入的节点为待删除节点(非尾节点,不考虑下一节点为空节点)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public void deleteNode(ListNode node) {
        node.val=node.next.val;
        node.next=node.next.next;
    }
}

阅读更多
换一批

没有更多推荐了,返回首页