反转堆栈并连接弹出的堆栈

时间:2017-11-26 04:41:40

标签: java arraylist stack push pop

我试图将任何数组列表反向推送到堆栈然后连接弹出的堆栈。我从文件中获取信息,然后将其存储到数组列表中。然后我将数组List推入堆栈。现在,当我打印出它只是打印数组列表时,如何弹出堆栈并连接它?这是我到目前为止的代码

public static LinkedListStack myStack = new LinkedListStack();

public static void main(String[] args)
{
    readFileLoadStack();
    popStackPrintMsg();
}

public static void readFileLoadStack()
{
  File afile;         // For file input
  Scanner keyboard = new Scanner(System.in); // For file input
  String fileName;   // To hold a file name
  String line;
  ArrayList song = new ArrayList<>();
  boolean fileNotFound = true;

  do
  {
          // Get a file name from the user.
      System.out.println("Enter the name of the file");
      fileName = keyboard.nextLine();
          // Attempt to open the file.
          try
          {
             afile = new File(fileName);
             Scanner inFile = new Scanner(afile);
             System.out.println("The file was found");
             fileNotFound = false;
             while (inFile.hasNextLine())
             {
                  song.add(line = inFile.next());
             }
             for(int i = 0; i < song.size(); i++)
                  {
                      myStack.push1(song);
                  }
          }
          catch (FileNotFoundException e)
          {
             fileNotFound = true;
          }
  } while (fileNotFound);
}
public static void popStackPrintMsg()
{
    if(!myStack.empty())
    {
        System.out.println(myStack.pop1());
    } else
    {
        System.out.println("Sorry stack is empty");
    }
}

输出现在看起来像这样:[玛丽,有,一个,小,羊羔,谁的,羊毛,是,白色,如,雪,到处都是,玛丽,去了,羔羊,是,当然,到,去]

我试图让它看起来像这样:

羔羊很少有玛丽

雪白色的羊毛是谁的

到处都是玛丽

肯定是羊肉

我为推送和弹出

制作了一个自定义类
{
   private Node first;

  /** 
     Constructs an empty stack.
  */
  public LinkedListStack()
  {  
     first = null;
  }

  /**
     Adds an element to the top of the stack.
     @param element the element to add
  */
  public void push1(Object element)
  {  
     Node newNode = new Node();
     newNode.data = element;
    newNode.next = first;
     first = newNode;
  }
   /**
     Removes the element from the top of the stack.
     @return the removed element
  */
  public Object pop1()
  {  
     if (first == null) { throw new NoSuchElementException(); }
     Object element = first.data;
     first = first.next;
     return element;
  }

  /**
     Checks whether this stack is empty.
     @return true if the stack is empty
  */
  public boolean empty()
  {
     return first == null;
  }

  class Node
  {  
     public Object data;
     public Node next;
  }

}

1 个答案:

答案 0 :(得分:0)

我修复了代码中的问题。这是工作版本以及一些评论。这假定文件中的句子用新行分隔,单词用空格分隔。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class GeneralTest {
    //You want the same ordering for sentences. This collection
    //therefore should be a list (or a queue)
    //I have not changed the name so you can see how it makes a
    //difference
    public static List<LinkedListStack> myStack = new ArrayList<>();

    public static void main(String[] args)
    {
        readFileLoadStack();
        popStackPrintMsg();
    }

    public static void readFileLoadStack()
    {
        File afile;         // For file input
        Scanner keyboard = new Scanner(System.in); // For file input
        String fileName;   // To hold a file name
        String line;
        ArrayList song = new ArrayList<>();
        boolean fileNotFound = true;

        do
        {
            // Get a file name from the user.
            System.out.println("Enter the name of the file");
            fileName = keyboard.nextLine();
            // Attempt to open the file.
            try
            {
                afile = new File(fileName);
                Scanner inFile = new Scanner(afile);
                System.out.println("The file was found");
                fileNotFound = false;
                while (inFile.hasNextLine())
                {
                    //Here you need to use nextLine() instead of next()
                    song.add(inFile.nextLine());
                }

                //This loop is the main location your original code goes wrong
                //You need to create a stack for each sentence and add it to the
                //list. myStack will hold a list of stacks after this loop is done
                for(int i = 0; i < song.size(); i++)
                {
                    String songString = (String) song.get(i);
                    String[] sga = songString.split(" ");
                    LinkedListStack rowStack = new LinkedListStack();
                    for(int j=0; j < sga.length; j++) rowStack.push1(sga[j]);
                    myStack.add(rowStack);
                }
            }
            catch (FileNotFoundException e)
            {
                fileNotFound = true;
            }
        } while (fileNotFound);
    }
    public static void popStackPrintMsg()
    {

        //To get all values in a collection you need to
        //loop over it. A single if will not work
        for(LinkedListStack rs : myStack)
        {
            //Each entry in the list is a LinkedListStack
            //So you can pop them and print the results with
            //appropriate separators
            while(!rs.empty())
                System.out.print(rs.pop1() + " ");
            System.out.println();
        }

    }
}

现在,您的代码还有许多其他问题。例如,在创建集合类时,您确实应该使用泛型。

您的代码的主要问题是,要生成您描述的输出,您将需要堆栈队列。我已使用ArrayList实现了该概念,以显示问题的根源。但是如果你想学习数据结构(或者这是一个家庭作业问题),那么你应该尝试实现并使用队列。