标题:Java手写双向链表
1.声明链表的节点样式:
class IntSNode{
public int info;
public IntSNode prev;
public IntSNode next;
public IntSNode(int info) {
this(info,null,null);
}
public IntSNode(int info,IntSNode prev,IntSNode next) {
this.info=info;
this.prev=prev;
this.next=next;
}
}
2.写一个类似LinkedList【为双向链表】的双向链表
class IntSNodeList{
private IntSNode head;
private IntSNode tail;
//后面可以增加一些列【增删改查】,可以见完整代码
}
完整代码如下:
/**
* 测试手写双向链表
* @author dell
*
*/
class IntSNode{
public int info;
public IntSNode prev;
public IntSNode next;
public IntSNode(int info) {
this(info,null,null);
}
public IntSNode(int info,IntSNode prev,IntSNode next) {
this.info=info;
this.prev=prev;
this.next=next;
}
}
class IntSNodeList{
private IntSNode head;
private IntSNode tail;
/**
* 向双向链表的头部添加--》值
* @param info
*/
public void addToHead(int info) {
IntSNode p=new IntSNode(info,null,head);
if(head==null) {
head=p;
tail=p;
}else {
head.prev=p;
head=p;
}
}
/**
* 向双向链表的尾部添加--》值
*/
public void addToTail(int info) {
IntSNode p=new IntSNode(info,tail,null) ;
if(tail==null) {
head=p;
tail=p;
}else {
tail.next=p;
tail=p;
}
}
/**
* 从双向链表的头部--》删除值
*/
public IntSNode deleteFromHead() {
IntSNode p=head;
if(head!=null) {
if(head==tail) {
head=null;
tail=null;
}else {
head=head.next;
head.prev=null;
}
}
return p;
}
/**
* 从双向链表的尾部--》删除值
*/
public IntSNode deleteFromTail() {
IntSNode p=tail;
if(tail!=null) {
if(head==tail) {
head=null;
tail=null;
}else {
tail=tail.prev;
tail.next=null;
}
}
return p;
}
/**
* 输出双向链表中的所有--》值
*/
public void printAllInfo() {
IntSNode p=head;
while(p!=null) {
System.out.print(p.info+" ");
p=p.next;
}
}
/**
* 【反向】输出双向链表的所有--》值
*/
public void printAllInfoByReverse() {
IntSNode p=tail;
while(p!=null) {
System.out.print(p.info+" ");
p=p.prev;
}
}
}
public class TestIntSNodeList {
public static void main(String[] args) {
IntSNodeList mySList = new IntSNodeList();
System.out.println("测试从头部向双向链表添加--》值");
mySList.addToHead(1);
mySList.addToHead(2);
mySList.addToHead(3);
mySList.addToHead(4);
mySList.printAllInfo();
System.out.println("测试从尾部--》添加值");
mySList.addToTail(7);
mySList.addToTail(8);
mySList.addToTail(9);
mySList.addToTail(10);
mySList.printAllInfo();
System.out.println("测试从头部--》删除值");
IntSNode p = mySList.deleteFromHead();
if(p!=null) {
System.out.println(p.info);
}
p = mySList.deleteFromHead();
if(p!=null) {
System.out.println(p.info);
}
mySList.printAllInfo();
System.out.println("测试从尾部--》删除值");
p=mySList.deleteFromTail();
if(p!=null) {
System.out.println(p.info);
}
p=mySList.deleteFromTail();
if(p!=null) {
System.out.println(p.info);
}
mySList.printAllInfo();
System.out.println("测试反转输出");
mySList.printAllInfoByReverse();
}
}