import java.util.ArrayList;
import java.util.List;
/** *//**
* 鏈表實現ADT
* @author BruceLeey
*/
class Node {
Object obj; //數值域
Node next; //鏈域
public Node() {
}
public Node(Object value) {
this.obj = value;
next = null;
}
}
class LinkList {
private Node first; //頭節點,不記錄在鏈表之內
private int size; //記錄鏈表節點長度
public LinkList() {
first = null;
size = 0;
}
/** *//**
* 添加節點
*
* @param value
*/
public void addNode(Object value) {
System.out.println("\n-------------------------添加節點 " + value + " -------------------------");
Node currentNode = new Node(value);
currentNode.next = first; //當前節點鏈域指向頭節點
first = currentNode; //頭節點記錄當前節點地址
size++;
}
/** *//**
* 驗證是否為空
* @return
*/
public boolean isEmpty() {
return size == 0;
}
/** *//**
* 刪除表頭
* @param value
*/
public Node removeFirstNode() {
System.out.println("\n-------------------------移除頭節點-------------------------");
Node temp = first;
first = first.next; //指向下一節點
size--;
System.out.println("\n移除的表頭數據為: " + temp.obj);
return temp; //返回刪除的節點
}
/** *//**
* 封裝長度
* @return
*/
public int getSize() {
return size;
}
/** *//**
* 找出索引之前的節點
* @param index
* @return
*/
public List<Node> getNodeByIndex(int index) {
System.out.println("\n-------------------------查找" + index + "之前的所有節點-------------------------");
List<Node> list = new ArrayList<Node>();
assert (!(index > getSize() - 1 || index < 0));
Node current = first; //定位到頭節點
for (int i = 0; i < index; i++) {
list.add(current);
current = current.next; //以此往下移
}
for (int j = 0; j < list.size(); j++) {
System.out.println("\n查找到的數據為: " + list.get(j).obj);
}
return list;
}
/** *//**
* 輸出鏈表
*/
public void displayNode() {
System.out.println("\n-------------------------開始輸出鏈表-------------------------");
assert (!this.isEmpty());
Node current = first;
for (int i = 0; i < getSize(); i++) {
System.out.println("節點為: " + current.obj.toString());
current = current.next;
}
}
}
public class TestAdt {
public static void main(String[] args) {
LinkList link = new LinkList();
for (int i = 0; i < 10; i++) {
link.addNode("我是節點 " + i);
}
link.displayNode();
Node node = link.removeFirstNode();
link.displayNode();
link.getNodeByIndex(5);
link.displayNode();
}
}
posted on 2009-09-26 14:38
Worker 閱讀(213)
評論(0) 編輯 收藏 所屬分類:
算法/數據結構