每个节点即有指向前一个节点的地址,还有指向后一个节点的地址;
/**
* @ClassName BothwayList
* @Description 双向链表
* @Author lzq
* @Date 2018/5/7 20:14
* @Version 1.0
**/
public class BothwayList {
class Entry {
private int data;
private Entry prev; //前驱
private Entry next; //后继
public Entry() {
this.data = -1;
this.next = null;
this.prev = null;
}
public Entry(int val) {
this.data = val;
this.next = null;
this.prev = null;
}
}
private Entry head;
public BothwayList(){
this.head = new Entry();
}
/**
* 头插法
* @param val
*/
public void head_insert(int val) {
Entry entry = new Entry(val);
entry.next = this.head.next;
this.head.next = entry;
entry.prev = this.head;
if(entry.next != null) {
entry.next.prev = entry;
}
}
/**
* 尾插法
* @param val
*/
public void tail_insert(int val) {
Entry entry = new Entry(val);
Entry cur = this.head;
while(cur.next != null) {
cur = cur.next;
}
cur.next = entry;
entry.prev = cur;
}
/**
* 删除所有值为val的节点
* @param val
*/
public void delete(int val) {
Entry cur = this.head;
while(cur.next != null) {
if(cur.next.data == val) {
cur.next = cur.next.next;
if(cur.next != null) {
cur.next.prev = cur;
}
continue;
}
cur = cur.next;
}
}
/**
* 打印
*/
public void show() {
Entry cur = this.head;
while(cur.next != null) {
cur = cur.next;
System.out.print(cur.data+"\t");
}
System.out.println();
}
}