双向链表
双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。
具体操作
属性
public DoubleLink start;
public DoubleLink last;
1.insertStart
public void insertStart(int v){
DoubleLink link = new DoubleLink(v);
if(start==null){
start=link;
last=link;
}else {
link.next=start;
start.prev=link;
start=link;
}
}
2.insertLast
public void insertLast(int v){
DoubleLink link = new DoubleLink(v);
if(last==null){
start=link;
last=link;
}else {
last.next=link;
link.prev=last;
last=link;
}
}
3.insertAfterKey
public void insertAfterKey(int key,int love){
DoubleLink link = new DoubleLink(love);
DoubleLink t = start;
DoubleLink p = t;
while (t!=null&&t.value!=key){
p = t;
t=t.next;
}
if(t==null){
System.out.println("key is error!");
}else {
if(t.next==null){
t.next=link;
link.prev=t;
last = link;
}else {
t.next.prev=link;
link.next=t.next;
t.next=link;
link.prev=t;
}
}
}
4.deleteStart
public int deleteStart(){
int v = start.value;
if (start.next==null){
start= null;
last = null;
}else {
start.next.prev=null;
start=start.next;
}
return v;
}
5.deleteLast
public int deleteLast(){
int v = last.value;
if(last.prev==null){
last=null;
start=null;
}else {
last.prev.next=null;
last=last.prev;
}
return v;
}
6.deleteByKey
public int deleteByKey(int key){
DoubleLink t = start;
DoubleLink p = t;
while (t!=null&&t.value!=key){
p = t;
t = t.next;
}
if(t==null){
System.out.println("key is error!");
return 0;
}else {
p.next=t.next;
t.next.prev=t.prev;
return t.value;
}
}
7.displayForward
public void displayForward(){
DoubleLink t = start;
while (t!=null){
System.out.println(t.value);
t=t.next;
}
}
8.displayBackward
public void displayBackward(){
DoubleLink t = last;
while (t!=null){
System.out.println(t.value);
t=t.prev;
}
}
9.DoubleLink类
public class DoubleLink {
public int value;
public DoubleLink next;
public DoubleLink prev;
public DoubleLink(int value) {
this.value = value;
}
}