203. Remove Linked List Elements - LeetCode

Question

203. Remove Linked List Elementsjava

Solution

題目大意:從鏈表中刪除給定的數code

思路:遍歷鏈表,若是該節點的值等於給的數就刪除該節點,注意首節點ip

Java實現:element

public ListNode removeElements(ListNode head, int val) {
    ListNode cur = head;

    while (cur != null) {
        if (cur.next != null && cur.next.val == val) {
            ListNode tmp = cur.next.next;
            cur.next = tmp;
        } else {
            cur = cur.next;
        }
    }
    return (head != null && head.val == val) ? head.next : head;
}
相關文章
相關標籤/搜索