1. 程式人生 > >Java 單鏈表簡單實現

Java 單鏈表簡單實現

pre println ret 返回 .data del span 鏈表 font

實現功能並不完全,只有添加,刪除,和遍歷功能,後續還會繼續添加

定義節點屬性

class Node{ //定義節點屬性
    public int Data;
    public Node next = null;
    public Node(int Data){
        this.Data = Data;
    }
}

定義節點方法

class ListMe {
    Node head = null;//頭結點為空
    
    void addNode(int data){ //添加節點
        Node newNode = new Node(data); //創建新節點
if(head == null){ //如果頭結點為空,就讓節點作為頭結點 head = newNode; return; } Node temp = head; while(temp.next!=null){ //讓節點遍歷都最後一個位置 temp = temp.next; } temp.next = newNode; //添加節點 } boolean delNode(int position){ //
刪除節點 if(position>listLength()||position<1){ //如果刪除的位置不在指定地方,就返回false return false; } if(position == 1){ //頭結點更換 head = head.next; return true; } int i = 1; Node preNode = head; //前驅節點 Node curNode = preNode.next; //
後一位節點 while(curNode != null){ //後一位不為空,就遍歷查找到指定位置的節點 if( i == position){ //查找到之後就讓前一位直接連到後一位節點位置上 preNode.next = curNode.next; return true; } preNode = curNode; //節點後推 curNode = curNode.next; i++;//位置 } return false; } int listLength(){ //返回鏈表長度 int length = 0; Node curNode = head; while(curNode != null){ length++; curNode = curNode.next; } return length; } void print(){ //打印鏈表內容 Node curNode = head; while(curNode != null){ System.out.print(curNode.Data+" "); curNode = curNode.next; } } }

主方法中測試數據

public class Main{
    public static void main(String[] args){
        ListMe a = new ListMe();
        a.addNode(2);
        a.addNode(1);
        a.addNode(5);
        a.addNode(4);
        a.addNode(3);
        a.print();
        System.out.println();
        System.out.println(a.listLength());
        if(a.delNode(1)){
            a.print();
       System.out.println(); System.out.println(a.listLength()); }
else{ System.out.println("異常"); } } }

以下是運行結果

2 1 5 4 3

5

1 5 4 3

4

Java 單鏈表簡單實現