链式存储与顺序存储相比较,更节省空间,更加方便的删除和插入
/**
* @author NEOSONG
* @date Oct 7, 2017
* 10:18:26 AM
* program OF information: 1.定义节点类
*/
class Node
{
private Node
next;//指针域
private T data;//数据域
//构造方法
//无参构造
public Node(){
next=null;
}
public Node(Node
next){//仅有指针域,无数据域
this.next=next;
}
public Node(T data){//仅有数据域,无指针域
this.data=data;
next=null;
}
public Node(T data,Node
next){//都有
this.data=data;
this.next=next;
}
public Node
getNext() { return next; } public void setNext(Node
next) { this.next = next; } public T getData() { return data; } public void setData(T data) { this.data = data; } } /** * @author NEOSONG * @date Oct 7, 2017 * 11:44:15 AM * program OF information: 2.定义链式表类 */ public class LinkList
{ //定义构造方法,以初始化变量 public LinkList(){ header=new Node
(); } //定义一个头结点 private Node
header; //set/get方法 public Node
getHeader() { return header; } public void setHeader(Node
header) { this.header = header; } //求长度 public int count(){ int i=0;//用于累加 Node
p=header; while(p.getNext()!=null){//循环遍历链式表中的元素 p=p.getNext(); i++; } return i; } //清空操作 public void clear(){ header.setNext(null); } //判断单链表是否为空 public boolean isEmpty(){ return header.getNext()==null; } //附加操作 public void attend(T data){ Node
p=new Node
(data);//需要附加的节点 Node
r=header;//用r遍历 while(r.getNext()!=null) r=r.getNext(); r.setNext(p); } //插入操作,i为位置 public void insert(T data,int i){ //为增强程序的健壮性,增加判断 //判断位置是否正确 if(i<1||i>count()) throw new RuntimeException("插入位置不正确"+i); Node
p=new Node
(data); Node
r=header; Node
q=new Node
(); for(int j=0;j
count()) throw new RuntimeException("删除位置不正确"+i); Node
r=header; Node
q=new Node
(); for(int j=0;j
count()) throw new RuntimeException("取值位置不正确"+i); Node
r=header; int n=1; while(n<=i){ r=r.getNext(); n++; } return r.getData(); } //定位,按值查找 public int locate(T data){ //增加判断 if(isEmpty()){ throw new RuntimeException("链式表为空,无法查询"); } Node
r=header; int i; for(i=1;i<=count();i++){ r=r.getNext(); if(r.getData()==data) break; else if(i==count()&&r.getData()!=data) throw new RuntimeException("抱歉,没有查询到这个值!"); } return i; } //输出链式表 public void printLinkList(){ if(isEmpty()){ throw new RuntimeException("链式表为空"); } Node
r=header; while(r.getNext()!=null){ r=r.getNext(); System.out.print(r.getData()+" "); } } }