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 阅读(203)
评论(0) 编辑 收藏 所属分类:
算法/数据结构