在实现linkedqueue的情况下,除了pop()方法外,所有方法都可以正常工作。当使用pop()方法时,堆栈中的所有值都消失了,当它仅删除第一个值
时,它将其为空这是Linkedqueue类
import java.util.NoSuchElementException;
public class LinkedQueue
{
Node front, rear;
int size;
public LinkedQueue()
{
front = null;
rear = null;
size = 0;
}
public boolean isEmpty()
{
if(front == null)
return true;
else
return false;
}
public int getSize()
{
return size;
}
public void push(int data)
{
Node n = new Node(data);
if(isEmpty())
front = rear = n;
else
{
rear.setLink(n);
rear = n;
}
size++;
}
public int pop()
{
Node temp = new Node(front.getData());
if(isEmpty())
{
throw new IllegalAccessError();
}
else
{
front = temp.getLink();
size--;
}
return temp.getData();
}
public int peek()
{
if (isEmpty())
{
throw new NoSuchElementException("Stack is empty.");
}
else
{
return front.getData();
}
}
public String toString()
{
Node tempFront = front;
String returnStr = "Stack: [";
while(tempFront != null)
{
returnStr += tempFront.getData() + ", ";
tempFront = tempFront.getLink();
}
returnStr += "]";
return returnStr;
}
}
这是用于Linkedqueue类的驱动程序:
import java.util.Scanner;
public class Driver
{
public static void main(String[] args)
{
//declare variables and initialize scanner
Scanner key = new Scanner(System.in);
int size, choice, value, end;
end = 0;
//declare and initialize the stack
LinkedQueue queue1 = new LinkedQueue();
//loop to continue operations
while(end == 0)
{
//print out menu for commands
System.out.println("t1) Push nt2) Pop nt3) Peek nt4) Size nt5) isEmpty nt6) End");
System.out.print("Please choose an option: ");
choice = key.nextInt();
//switch the choice and execute commands
switch (choice)
{
case 1: System.out.println("Please enter a value: ");
value = key.nextInt();
queue1.push(value);
System.out.println(queue1.toString());
break;
case 2: queue1.pop();
System.out.println(queue1.toString());
break;
case 3: queue1.peek();
System.out.println(queue1.peek());
System.out.println(queue1.toString());
break;
case 4: System.out.println("Size: " + queue1.getSize());
System.out.println(queue1.toString());
break;
case 5: if(queue1.isEmpty())
{
System.out.println("Stack is empty.");
}
else
System.out.println("Stack is NOT empty.");
System.out.println(queue1.toString());
break;
case 6: end = 1;
System.out.println("Goodbye!");
break;
}
}
}
}
我也做了自己的节点类
public class Node
{
int data;
Node link;
//contructor
public Node(int d)
{
data = d;
link = null;
}
public int getData()
{
return data;
}
public Node getLink()
{
return link;
}
public void setData(int d)
{
data = d;
}
public void setLink(Node n)
{
link = n;
}
}
如前所述,我唯一的问题是POP()方法,但是如果您看到其他也将有所帮助的错误,这将不胜感激。
替换
front = temp.getLink();
front = front.getLink();