链表是一种基本的数据结构,与数组相比链表存储数据更为灵活。在本实例中,实现的是链表结构,使用Java语言实现。
链表类的设计,链表由链节点构成,每个链节点分别由数据域(value)和节点域(next)组成,数据域用于存储数据,节点域用于指向下一个节点。
class Node{
int value;//数据域
Node next;//节点域
public Node(int data){
this.value=data;//节点类构造函数
}
}
public class LinklistNode {
Node node;//节点
public LinklistNode(){
this.node=null;//链表构造函数
}
public Node initLinklist(int data){
Node temp;
temp=new Node(data);
temp.next=this.node;
this.node=temp;
return this.node;
}//初始化链表,建立头结点
public void addNode(int data){
Node temp;
temp=new Node(data);
temp.next=this.node;
this.node=temp;
temp=null;
}//增添数据,使用从链表头部进行插入
public int selectNode(int pos){
Node current;
int p=0;
current=this.node;
while(p<=pos-1&¤t!=null){
current=current.next;
p++;
}
return current.value;
}//根据输入位置返回指定位置的数据值
public int deleteNode(){
Node temp;
temp=this.node;
this.node=temp.next;
return temp.value;
}//删除节点
public void printLinklistNode(){
Node current;
current=this.node;
while(current!=null){
System.out.print(current.value+" ");
current=current.next;
}//输出链表数据
}
}
测试主函数代码
public class testLinklist {
public static void main(String[] args) {
// TODO Auto-generated method stub
LinklistNode head=null;
head=new LinklistNode();
head.initLinklist(5);//生成头结点
for(int i=0;i<5;i++){
head.addNode(i);//添加节点
}
head.printLinklistNode();//输出链表
System.out.println();
head.deleteNode();//删除链表节点
head.printLinklistNode();
System.out.println();
head.deleteNode();
head.printLinklistNode();
System.out.println();
System.out.println("pos 2 value:"+head.selectNode(2));//输出指定位置的节点数据值
}
}
测试效果图示: