1. 程式人生 > 其它 >覆蓋全網的阿里微服務架構有多牛:K8S+實戰+筆記+專案教程

覆蓋全網的阿里微服務架構有多牛:K8S+實戰+筆記+專案教程

public class Algorithm {

    public static void main(String[] args) {

        int[] arr = {1, 2, 6, 3, 4, 5, 6};
        ListNode head = new ListNode(arr);

        System.out.println(head);
        System.out.println(new Solution().removeElements(head, 6));
    }
}

class Solution {
    public ListNode removeElements(ListNode head, int val) {

        /**
         * 涉及到連結串列遍歷,使用虛擬頭節點更方便
         */
        ListNode dummyHead = new ListNode();
        dummyHead.next = head;

        ListNode prev = dummyHead;

        while (prev.next != null){
            if (prev.next.val == val){

                ListNode tem = prev.next;
                prev.next = tem.next;
                tem.next = null;
            }
            else {
                prev = prev.next;
            }
        }

        return dummyHead.next;
    }
}

/**
 * ListNode類是節點類
 * 其物件只是一個節點,而不是連結串列
 */
class ListNode {

    public int val;
    public ListNode next;

    public ListNode(int val, ListNode next) {

        this.val = val;
        this.next = next;
    }

    public ListNode(int val) {

        this.val = val;
    }

    public ListNode(){}

    /**
     * 在構造方法里根據一個數組來構建連結串列
     */
    public ListNode(int[] arr){

        if (arr == null || arr.length == 0){
            throw new IllegalArgumentException("陣列是空的");
        }

        /**
         * this指這個ListNode物件
         * 將其設定為這個連結串列的頭節點,就可以根據頭節點生成連結串列了
         */
        this.val = arr[0];
        ListNode prev = this;

        for (int i = 1; i < arr.length; i++) {

            prev.next = new ListNode(arr[i]);
            prev = prev.next;
        }
    }

    /**
     * 當列印頭節點物件時,就會打印出整個連結串列
     */
    @Override
    public String toString(){

        StringBuilder str = new StringBuilder();

        ListNode curr = this;
        while (curr != null){
            str.append(curr.val + "——>");
            curr = curr.next;
        }
        str.append("null");

        return str.toString();
    }
}

https://leetcode-cn.com/problems/remove-linked-list-elements/