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

單鏈表實現

== next data sys code new public 元素 --

package com.wyl.linklist;

public class MyLinkList {

    private Node head;  //鏈表的起始節點
    private int size = 0; //記錄鏈表的長度
    /**
     * 定義內部節點類
     * @author wyl
     *
     */
    class Node {

        private String name;  //節點的內容
        private Node next; //指向節點的直接後繼
        
        public Node(){
            
        }
        
public Node(String name){ this(name, null); } public Node(String name, Node next) { this.name = name; this.next = next; } } /** * 初始化鏈表,創建頭結點 */ public MyLinkList(){ head = new Node(); //頭結點為空節點 head.next = null
; } /** * 給鏈表中增加節點 * @param data */ public void addNode(String data){ /* 1、獲取表頭 * 2、通過表頭找到最後一個元素 * 3、將新增的節點放到最後一個節點的後面 * */ Node p = head; while(p.next != null){ p = p.next; //移動指針,永遠指向鏈表尾部 } p.next = new
Node(data); size++ ; } /*刪除節點*/ public void delNode(String data){ /* 1、獲取表頭 * 2、通過表頭找到最後一個元素 * 3、將新增的節點放到最後一個節點的後面 * */ if(head.next == null){ return; } Node p = head; while(p.next != null){ if(p.next.name.equals(data)){ p.next = p.next.next; size--; break; }else{ p = p.next; } } } /*查找數據是否在鏈表中*/ public boolean contains(String data){ Node p = head; while(p.next != null){ if(p.next.name.equals(data)){ return true; }else{ p = p.next; } } return false; } /*在指值的後面插入值*/ public void insertNode(String param, String data){ Node p = head; while(p.next != null){ if(p.next.name.equals(param)){ Node temp = p.next.next; Node newNode = new Node(data, temp); p.next.next = newNode; return; }else{ p = p.next; } } } /*鏈表遍歷*/ public void iterator(){ Node p = head; if(p.next == null){ System.out.println("空鏈表"); } p = p.next; while(p.next != null){ System.out.print(p.name + "==>>"); p = p.next; } System.out.print(p.name); } /*鏈表長度*/ public int size(){ return size; } public static void main(String[] args) { MyLinkList myLinkList = new MyLinkList(); myLinkList.addNode("組長"); myLinkList.addNode("部門經理"); myLinkList.addNode("主管副總"); myLinkList.addNode("總經理"); myLinkList.iterator(); System.out.println(); myLinkList.delNode("部門經理"); myLinkList.iterator(); System.out.println(); myLinkList.insertNode("主管副總", "經理"); myLinkList.iterator(); } }

單鏈表實現