双向链表也叫头尾链表,头尾链表可以在头结点和尾结点分别进行插入和删除操作
首先建立结点类,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| package firstlastlist;
public class Node{ int data; public Node next; public Node privious; public Node(int value){ this.data=value;
} public void display(){ System.out.println(data+" "); } }
|
操作代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| package firstlastlist; public class FirstLastList { Node first; Node last; public FirstLastList(){ first=null; last=null; } public boolean isEmpty(){ return first==null; } public void insertFirst(int value){ Node node=new Node(value); if(isEmpty()){ last=node; }
node.next=first; first=node; } public void insertlast(int value){ Node node=new Node(value); if(isEmpty()){ first=node; } else{ last.next=node; } last=node; } public int deletFirst(){ if(first.next==null){ last=null; } Node temp=first; first=first.next; return temp.data; } public void display(){ Node t=first; while(t.next!=null){ t.display(); t=t.next; } t.display();; } public Node chazhao(int value){ Node tt=first; while(tt.data!=value){ if(tt.next==null){ return null; } tt=tt.next; } return tt; } public Node shangchu(int value){ Node tt=first; Node ty=first; while(tt.data!=value){ if(tt.next==null){ return null; } ty=tt; tt=tt.next; } if(tt==first){ first=first.next; } else{ ty.next=tt.next; } return tt; } }
|
测试代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| package firstlastlist;
public class TestFirstlastList { public static void main(String args[]){ FirstLastList tt=new FirstLastList(); tt.insertFirst(1); tt.insertFirst(2); tt.insertFirst(3); tt.display(); tt.deletFirst(); tt.display(); } }
|
运行结果如下所示:
3
2
1
2
1