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;
}
相关文章
相关标签/搜索