java初學(3) 單鏈表——頭插法

 

/**
 * 
 */
package com.wan.xiang.LinkList;

/**
 * @author Sakura
 * @Desc //TODO 鏈表類
 * @Date 2019年7月21日下午3:59:00
 */
public class LinkList {
	
	Node first;//頭結點
	Node last;//尾結點
	public LinkList() {
		//構造帶頭結點的鏈表
		first = new Node();
		last = first;
	}
	public void addNode(Object data) {
		Node temp = new Node(data);
		if(last == first) {
			//如果鏈表中只有一個頭結點
			first.next = temp;
			last = temp;
		}else {
			//頭插法
			temp.next = first.next;
			first.next = temp;
		}
		
	}
	@Override
	//重寫toString 輸出鏈表
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		Node temp;
		temp = first.next;//頭結點沒有數據,從首元結點開始遍歷
		if (temp == null) {
			return "{null}";//鏈表爲空返回空鏈表
		} else {
			while (temp != null) {
				sb.append(temp.data + ",");
				temp = temp.next;
			}
			sb.setCharAt(sb.length() - 1, '}');//將最後一個逗號替換爲“}”
			return sb.toString();
		}
		
	}
	public static void main(String[] args) {
		LinkList list = new LinkList();
		list.addNode("a");
		list.addNode("b");
		System.out.println(list);
	}

}
/**
 * 
 */
package com.wan.xiang.LinkList;

/**
 * @author Sakura
 * @Desc //TODO Node class
 * @Date 2019年7月21日下午3:57:39
 */
public class Node {
	Object data;//data filed
	Node next;//指針 filed
	public Node() {
		next = null;
	}
	public Node(Object data) {
		this.data = data;
		next = null;
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章