1. 程式人生 > 其它 >Java程式設計題——簡單實現List操作

Java程式設計題——簡單實現List操作

技術標籤:Java程式設計題java

實現一些List的基本操作:

package List;

public class Node {
    public int val;
    public Node next;

    public Node(int val) {
        this.val = val;
    }

    @Override
    public String toString() {
        return " " + this.val;
    }
}
package List;

public class Main
{ public static Node creatList(){ Node a = new Node(1); Node b = new Node(2); Node c = new Node(3); Node d = new Node(4); Node e = new Node(5); a.next = c; c.next = e; e.next = d; d.next = b; return a; } public
static void main(String[] args) { Node head = creatList(); // 1. System.out.println("列印連結串列的每個元素:"); for (Node cur = head; cur != null; cur = cur.next){ System.out.print(cur + " "); } } }

在這裡插入圖片描述
測試2:

    public static void main(String[
] args) { Node head = creatList(); System.out.println("找到連結串列的最後一個結點:"); Node cur = head; while (cur != null && cur.next != null){ cur = cur.next; } System.out.println(cur.val); }

在這裡插入圖片描述
測試3:

    public static void main(String[] args) {
        Node head = creatList();
        System.out.println("找到連結串列的倒數第二個結點:");
        Node cur = head;
        while (cur != null && cur.next != null && cur.next.next != null){
            cur = cur.next;
        }
        System.out.println(cur.val);        
    }

在這裡插入圖片描述
測試4:

    public static void main(String[] args) {
        Node head = creatList();
        System.out.println("找到連結串列的倒數第二個結點:");
        Node cur = head;
        while (cur != null && cur.next != null && cur.next.next != null){
            cur = cur.next;
        }
        System.out.println(cur.val);        
    }

在這裡插入圖片描述
測試5:

    public static void main(String[] args) {
        Node head = creatList();
        System.out.println("計算連結串列中元素的個數:");
        int count = 0;
        for (Node cur = head; cur != null; cur = cur.next){
            count++;
        }
        System.out.println(count);                
    }

在這裡插入圖片描述
測試6:

    public static void main(String[] args) {
        Node head = creatList();
        System.out.println("找到連結串列中是否包含某個元素:");
        int findVal = 5;
        int index = 1;
        Node cur = head;
        for (; cur != null; cur = cur.next){
            if (cur.val == findVal){
                break;
            }
            index++;
        }
        if (cur == null){
            System.out.println("未找到為 " + findVal + " 的值");
        }else {
            System.out.println("已找到為 " + findVal + " 的值");
            System.out.println("該值在連結串列的第 " + index + " 位");
        }              
    }

在這裡插入圖片描述

當 findVal 為 0 時:
在這裡插入圖片描述