堆栈和数据结构

时间:2016-09-21 18:41:55

标签: java data-structures stack

我正在为类做一个任务,它要求我使用实现基本堆栈数据结构的Java编程语言开发算法。

以下是场景:假设您正在为制造汽车的制造装配线开发系统。生产线上有三个工位,检查员将目视检查车辆。您的程序必须在发生这些检查时跟踪它们。您决定使用堆栈数据结构开发程序。当您的车辆开始行时,您将向后三次将数字0(表示尚未进行检查)推入堆栈。在该行中的每个站点,您将从堆栈中弹出其中一个项目。每次算法从堆栈中弹出一个项目时,您必须使用system.out.println函数将其打印到控制台。我将在下面发布我的代码。我的代码是代表这个senario吗?

我的代码:

import jeliot.io.*;

public class MyStack {
   private int maxSize;
   private long[] stackArray;
   private int top;
   public MyStack(int s) {
      maxSize = s;
      stackArray = new long[maxSize];
      top = -1;
   }
   public void push(long j) {
      stackArray[++top] = j;
   }
   public long pop() {
      return stackArray[top--];
   }
   public long peek() {
      return stackArray[top];
   }
   public boolean isEmpty() {
      return (top == -1);
   }
   public boolean isFull() {
      return (top == maxSize - 1);
   }
   public static void main(String[] args) {
      MyStack theStack = new MyStack(5); 
      theStack.push(0);
      theStack.push(1);
      theStack.push(2);
      theStack.push(3);
      theStack.push(4);
      while (!theStack.isEmpty()) {
         long value = theStack.pop();
         System.out.print(value);
         System.out.print(" ");
      }
      System.out.println("");
   }
 }

该作业还附带了一个链表示例代码。您可以比较我的代码的工作方式。这是代码:

import Prog1Tools.IOTools;

class Node {
   Node ptr;
   int value;
   public Node(int value) {
     this.value = value;
   }
}

public class CreateLinkedList {
  public static void main(String[] args) {
    Node link, plink;
    // root will be the beginning of the linked list
    Node root = new Node(5);
    // each additional node will link to preceeding one
    link = new Node(1);
    link.ptr = root;
    plink = link;

    link = new Node(8);
    link.ptr = plink;
    plink = link;

    link = new Node(6);
    link.ptr = plink;
    plink = link;

    link = new Node(3);
    link.ptr = plink;
    plink = link;

    // Move through the list and print out each value
    printList(link);
}

public static void printList(Node node) {
  if (node != null) {
    System.out.println(" Value: " + node.value);
    printList(node.ptr);
    }
  }
}

2 个答案:

答案 0 :(得分:0)

是的,堆栈数据结构已经很好地实现了。

答案 1 :(得分:0)

或者你可以扩展已经存在的堆栈实现来添加一些特定的行为(比如打印出弹出的元素)

https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html