我写的一个java的单链表,可以从表头插入Node,比较简单,可以再扩充功能!!
package com.hukefeng.lang;
import java.util.*;
public class LangTest {
/**
* @param args
*/
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
NodeList nl=new NodeList();
nl.insertNode("Hello");
nl.insertNode("World");
nl.insertNode("and");
nl.insertNode("Hu kefeng");
System.out.println("Length of the Nodelist: "+nl.getLength());
nl.listNode();
}
}
class Node {
private Object obj = null;
public Node next = null;
public Node(Object obj) {
this.obj = obj;
}
public Object getObj() {
return obj;
}
}
class NodeList {
// define the pointer of the linklist
private Node head = null;
private int Length = 0;
public void listNode() {
Node pointer=head;
while (pointer != null) {
System.out.println(pointer.getObj().toString());
pointer=pointer.next;
}
}
/**
* @return
* @author hukefeng
*
*/
public boolean isEmpty() {
return head == null;
}
// insert the node
public void insertNode(Object obj) {
Node node=new Node(obj);
node.next=head;
head=node;
Length++;
}
/**
* @author Hu kefeng
*
* @return Node
*/
public Node deleteNode() {
Node temp = null;
if (head == null) {
throw new NoSuchElementException();
}
if (head != null) {
temp = head.next;
head = head.next;
}
return temp;
}
public void deleteAll() {
this.Length = 0;
this.head = null;
}
public int getLength() {
return Length;
}
}