编程导航算法村第五关 | 使用链表实现栈

编程导航算法村第五关 | 使用链表实现栈

  • 入队
    • 在链表的末尾添加节点
  • 出队
    • 在链表的起始位置删除节点数据
public class ImplementStacksBasedOnLinked {
    private ListNode head;
    private int size;

    /**
     * 初始化链表
     */
    public ImplementStacksBasedOnLinked() {
        this.head = new ListNode(0);
        this.size = 0;
    }

    /**
     * 入队
     */

    public void push(int data) {
        ListNode newNode = new ListNode(data);
        ListNode temp = head;
        while (temp.next != null) {
            temp = temp.next;

        }
        temp.next = newNode;

        size++;

    }

    /**
     * 入队
     */

    public int pop() {
//      删除head后一个元素
        if (size == 0) {
            return -1;
        }
        ListNode next = head.next;
        head.next = head.next.next;
        size--;
        return next.val;
    }

    /**
     * 遍历队列
     */
    public void display() {
        ListNode temp = head.next;
        while (temp != null) {
            System.out.print(temp.val);
            if (temp.next != null) {
                System.out.print(",");
            }
            temp = temp.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        final ImplementStacksBasedOnLinked implementStacksBasedOnLinked = new ImplementStacksBasedOnLinked();
        implementStacksBasedOnLinked.push(1);
        implementStacksBasedOnLinked.push(2);
        implementStacksBasedOnLinked.push(3);
        implementStacksBasedOnLinked.push(4);
        System.out.println(implementStacksBasedOnLinked.pop());
        System.out.println(implementStacksBasedOnLinked.pop());
        System.out.println(implementStacksBasedOnLinked.pop());
        System.out.println(implementStacksBasedOnLinked.pop());
        System.out.println(implementStacksBasedOnLinked.pop());
        System.out.println(implementStacksBasedOnLinked.pop());
        implementStacksBasedOnLinked.display();

    }
}

你可能感兴趣的:(算法,链表,javascript)