关于java:LeetCode203移除链表元素

4次阅读

共计 1007 个字符,预计需要花费 3 分钟才能阅读完成。

移除链表元素

题目形容:给你一个链表的头节点 head 和一个整数 val,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点。

示例阐明请见 LeetCode 官网。

起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl…
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

解法一:链表遍历

首先,初始化一个结点 firstNode 指向 head 结点,cur 指向 head 结点,last 指向 firstNode 结点,而后开始遍历:

  • 首先 cur 不能为空;
  • 如果 cur 结点的值等于目标值 val,则将 last 的 next 指向 cur 的 next,并且 cur 赋值为 cur 的 next;
  • 如果 cur 结点的值不等于目标值 val,则将 last 和 cur 结点往后移一位。

遍历完结后,返回 firstNode 的 next 结点即为解决后的链表。

public class LeetCode_203 {public static ListNode removeElements(ListNode head, int val) {ListNode firstNode = new ListNode(-1);
        firstNode.next = head;
        ListNode cur = firstNode.next;
        ListNode last = firstNode;
        while (cur != null) {if (cur.val == val) {
                last.next = cur.next;
                cur = last.next;
            } else {
                last = cur;
                cur = cur.next;
            }
        }
        return firstNode.next;
    }

    public static void main(String[] args) {ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(6);
        head.next.next.next = new ListNode(3);
        head.next.next.next.next = new ListNode(6);

        removeElements(head, 6);
        while (head != null) {System.out.print(head.val + " ");
            head = head.next;
        }
    }
}

【每日寄语】 在这个并非尽如人意的世界上,怠惰会失去报偿,而不务正业则要受到惩办。

正文完
 0