package dataStruct.test;
/**
* 节点,链式存储结构
* @author spirit
*
*/
public class NodeOne {
private String value;
private NodeOne next;
public NodeOne(){
}
public NodeOne(String value,NodeOne node){
this.value = value;
this.next = node;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public NodeOne getNext() {
return next;
}
public void setNext(NodeOne next) {
this.next = next;
}
}
package dataStruct.test;
/**
*
* @author spirit
*
*/
public class SingleLinkList {
private NodeOne header = null;
private NodeOne ender = null;
private int size ;
/**
* 完成初始化的过程
*/
public SingleLinkList(){
header = new NodeOne();
header.setNext(header);
ender = header;
size = 0;
}
/**
* 单向循环链表
* index:索引号
* value:待插入的值
*/
public boolean listInsert(int index,String value){
if(index < 0 || index > size) {
System.out.println("索引号越界");
return false;
}
if(index == size){
NodeOne p = new NodeOne(value,ender.getNext());
ender.setNext(p);
ender = p;
size ++;
return true;
}
NodeOne temp = header;
for(int i = 0; i < index;i++) {
temp = temp.getNext();
}
NodeOne n = new NodeOne(value,temp.getNext());
temp.setNext(n);
size++;
return true;
}
/**
* 不带索引值只播放到最后面
* @param value
* @return
*/
public boolean listInsert(String value){
return listInsert(size, value);
}
/**
* 带索引号的删除
* @param index
* @return
*/
public boolean listDelete(int index){
if(index < 0 || index > size) {
System.out.println("索引号越界");
return false;
}
NodeOne temp = header;
for(int i = 0; i < index;i++) {
temp = temp.getNext();
}
NodeOne p = temp.getNext();
temp.setNext(p.getNext());
p.setNext(null);
size--;
if(index == size) {
ender = temp;
return true;
}
return true;
}
/**
* 不带索引值,默认删除第一个
* @return
*/
public boolean listDelete(){
return listDelete(0);
}
/**
* 根据值来查找节点
* @param value
* @return
*/
public NodeOne listFind(String value){
NodeOne n = header;
for(int i = 0; i < size;i++) {
n = n.getNext();
if(n.getValue().equals(value)) {
return n;
}
}
System.out.println("没发现含有此数据的节点");
return null;
}
/**
* 按索引号来查值
* @param index
* @return
*/
public NodeOne listFind(int index){
if(index < 0|| index > size) {
System.out.println("索引号越界");
return null;
}
NodeOne n = header;
for(int i = 0; i < index;i++) {
n = n.getNext();
}
return n;
}
/**
* 打印方法
*/
public void print(){
if(size==0){
System.out.println("链表中无数据!");
return;
}
NodeOne temp = header;
System.out.print("[");
for(int i = 0; i < size;i++) {
temp = temp.getNext();
System.out.print(""+temp.getValue()+" ");
}
System.out.println("]");
}
public static void main(String[] args){
SingleLinkList list = new SingleLinkList();
//System.out.println(list.header.getValue()); 这里header中是无值的
// System.out.println(list.ender.getValue()); 同样,ender中也是无值的
for(int i = 0; i < 10; i++) {
list.listInsert(String.valueOf(i));
}
list.print();
list.listDelete(2); //删除索引号为2的值
list.print();
NodeOne n = list.listFind("4"); //按数据查询
if(n != null) {
System.out.println(n.getValue()+" --- "+n.getNext().getValue());
}
}
}