//实现双链 head 输出 输入 tail 输出输入 public static class Node<V>{ public V value; public Node<V> next; public Node<V> last; public Node(V v){ this.value=v; this.next=null; this.last=null; } } public static class MyDeque<V> { private Node<V> head; private Node<V> tail; private int size; public MyDeque() { head = null; tail = null; size = 0; } public boolean isEmpty() { return size == 0; } public int size() { return size; } public void pushHead(V value) { Node<V> cur = new Node<>(value); if (head == null) { head = cur; tail = cur; } else { cur.next = head; head.last = cur; head = cur; } size++; } public void pushTail(V value) { Node<V> cur = new Node<>(value); if (head == null) { head = cur; tail = cur; } else { tail.next = cur; cur.last = tail; tail = cur; } size++; } public V pollHead() { V ans = null; if (head == null) { return ans; } size--; ans = head.value; if (head == tail) { head = null; tail = null; } else { head = head.next; head.last = null; } return ans; } public V pollTail() { V ans = null; if (head == null) { return ans; } size--; ans = tail.value; if (head == tail) { head = null; tail = null; } else { tail = tail.last; tail.next = null; } return ans; } public V peekHead() { V ans = null; if (head != null) { ans = head.value; } return ans; } public V peekTail() { V ans = null; if (tail != null) { ans = tail.value; } return ans; } } public static Node<Integer> customDb(Node<Integer> head){ Node<Integer> result=null; Node<Integer> pre=null; for(int i=0;i<5;i++){ Node<Integer> cur= new Node<Integer>(i); if(head==null){ head=cur; pre=cur; result=cur; }else{ head.next=cur; cur.last=pre; pre=cur; head=cur; } } return result; } public void pollHead(Node<Integer> head){ int ans=-1; while(head!=null){ ans=head.value; head=head.next; System.out.println(ans); } } public void customDbTail(){ Node<Integer> head=null; Node<Integer> tail=null; for(int i=0;i<5;i++){ Node<Integer> cur=new Node<>(i);//0 if(head==null){ head=cur;//0 tail=cur;//0 }else{ tail.next=cur; cur.last=tail; tail=cur; } } } @Test void contextLoads(){ //双链 从头部加 从尾部加 //双链 从头部出 从尾部出 //从头部加 Node<Integer> head=customDb(null); //从头部出 pollHead(head); System.out.println("==================="); //从尾部加 customDbTail(); System.out.println("==================="); MyDeque<Integer> myDeque = new MyDeque<>(); for(int i=0;i<5;i++) myDeque.pushHead(i); for(int i=0;i<5;i++) System.out.println(myDeque.pollHead()); System.out.println("==================="); for(int i=0;i<5;i++) myDeque.pushTail(i); for(int i=0;i<5;i++) System.out.println(myDeque.peekTail()); }
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交