需要两个类 一个是node节点类 需要保存数据和下一个节点指向,代码如下
public class Node {
Object data;
Node next;
public Node() {
this.data = null;
this.next = null;
}
public Node(Object data) {
this.data = data;
}
}
另一个是单链表类 如下:
public class SingleChain {
Node head;
Node rear;
public SingleChain() {
this.head = new Node();
this.rear = this.head;
}
/**
* 首部插入
*/
public void insertHead(Node node){
//链表为空时直接使用尾插法
if(this.head.next ==null && this.rear.next==null ){
insertRear(node);
return;
}
node.next = this.head.next ;
this.head.next = node;
}
/**
* 尾部插入
*/
public void insertRear(Node node){
this.rear.next = node;
this.rear = node;
}
/**
* 固定位置前写入
*/
public void insertBefore(Node position,Node node){
Node p = this.head;
while (p!=null && !p.next.data.equals(position.data)){
p = p.next;
}
node.next = p.next;
p.next = node;
}
/**
* 固定位置后写入
*/
public void insertAfter(Node position,Node node){
Node p = this.head.next;
while (p!=null && !p.data.equals(position.data)){
p = p.next;
}
node.next = p.next;
p.next = node;
}
/**
* 获取链表长度
*/
public int getLength(){
int len = 0;
Node p = this.head.next;
while(p!=null){
len++;
p = p.next;
}
return len;
}
/**
* 获取节点索引值
*/
public int getIndexOfNode(Node node){
Node p = this.head.next;
int index = 0;
while (p!=null && !node.data.equals(p.data)){
index++;
p= p.next;
}
return index;
}
/**
* 反转
*/
public SingleChain convert(){
SingleChain convert = new SingleChain();
Node p = this.head.next;
Node cp = convert.head;
while (p!=null){
Node node = new Node(p.data);
node.next = cp.next;
cp.next = node;
p = p.next;
}
return convert;
}
public void printAll(){
Node p = this.head.next;
while (p!=null){
System.out.print(p.data+"\t");
p = p.next;
}
System.out.println();
}
public static void main(String[] args) {
Node A = new Node("A");
Node B = new Node("B");
Node C = new Node("C");
Node D = new Node("D");
Node E = new Node("E");
Node F = new Node("F");
SingleChain list = new SingleChain();
list.insertHead(D);
list.printAll();
list.insertRear(A);
list.printAll();
list.insertHead(B);
list.insertRear(C);
list.printAll();
list.insertBefore(A,E);
list.printAll();
list.insertAfter(A,F);
list.printAll();
System.out.println("length:"+list.getLength());
System.out.println("index of 'A':"+list.getIndexOfNode(A));
list.convert().printAll();
}
}