數據結構之鏈表

class Node{

    int val;
    Node next;

    Node(int val){
       this.val = val;
    }
}

一、棧(Stack)java

class Stack{
    Node top;
    
    Node peek(){
       if(null != top){
           return top;
       }
       return null;
    }


     void push(Node e){
         if(null != top){
            e.next = top;
            top = e;
         }
     }

     Node pop(){
        if(null == top){
            return null;
        }else{
            Node temp = new Node(top.val);
            top = top.next;
            return temp;
        }
     }
}
二、隊列(Queue)

class Queue{
   Node first,last;

   void enqueue(Node e){
      if(null == first){
         first = e;
         last = first;
      }else{
         last.next = e;
         last = e;
      }
   }

    Node dequeue(){
        if(null == first){
           return null;
        }else{
           Node temp = new Node(first.val);
           first= first.next;
           return temp;
        }
    }
}
相關文章
相關標籤/搜索