链表---使用链表实现栈和队列

在Java中,链表的实现非常简单,每个节点Node都有一个值val和指向下个节点的链接next。

节点的定义:

class Node {
    int val;
    Node next;
    Node(int x) {
        val = x;
        next = null;
    }
}

栈的实现:

class Stack{
    Node top;
    public Node peek(){
        if(top != null){
            return top;
        }
        return null;
    }
    public Node pop(){
        if(top == null){
            return null;
        }else{
            Node temp = new Node(top.val);
            top = top.next;
            return temp;   
        }
    }
    public void push(Node n){
        if(n != null){
            n.next = top;
            top = n;
        }
    }
}

队列的实现:

class Queue{
    Node first, last;

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

    public Node dequeue(){
        if(first == null){
            return null;
        }else{
            Node temp = new Node(first.val);
            first = first.next;
            return temp;
        } 
    }
}

猜你喜欢

转载自blog.csdn.net/l1394049664/article/details/81350190