英文:
How to implement a stack data structure into a linked list?
问题
我仍在学习如何正确使用链表,在我的CSCI 1302课程中,如果我做错了什么,请告诉我。我想使用push()和pop()操作实现一个堆栈数据结构。我仍需要构建驱动程序类,但我希望有人可以指导我在代码中哪里可以实现这两个操作。
import java.util.*;
public class myStack {
private class Node {
public int data;
public Node next;
public Node(int data) {
next = null;
this.data = data;
}
}
private Node head; // 添加这行用于声明head节点
public myStack() {
head = null;
}
public void push(int keydata) {
Node temp = new Node(keydata);
temp.next = head;
head = temp;
}
public int pop() {
if (head == null) {
throw new EmptyStackException();
}
int poppedValue = head.data;
head = head.next;
return poppedValue;
}
public void print() {
for (Node current = head; current != null; current = current.next) {
System.out.print(current.data + " ");
}
System.out.println();
}
public String toString() {
Node current = head;
String output = "";
while (current != null) {
output += "[" + current.data + "]";
current = current.next;
}
return output;
}
}
注意:我添加了push()
和pop()
方法来实现堆栈操作。push()
方法将新节点添加到链表的头部,模拟元素入栈。pop()
方法从链表头部移除节点并返回其值,模拟元素出栈。
英文:
I'm still learning how to use LinkedList, in my CSCI 1302 course, correctly so let me know if I am doing something wrong. I want to implement a stack data structure using the operations push() and pop(). I still need to build the driver class, but I was hoping someone could show me where I could implement these two operations within my code.
import java.util.*;
public class myStack {
private class Node
{
public int data;
public Node next;
public Node(int data)
{
next = null;
this.data = data;
}}
public LinkedDesign() //Linkedlist constructor
{
head = null;
}
public void add(int keydata) //add new value to the end of linked list
{
Node temp = new Node(keydata);
Node current = head;
if(head == null)
head = temp;
else
{
while(current.next != null)
{
current = current.next;
}
current.next = temp;
}
}
public void print()
{
// from head to tail, print each node's data
for (Node current = head; current != null; current = current.next)
{
System.out.print(current.data + " ");
}
System.out.println();
}
// toString(): print data in the linked list
public String toString()
{
Node current = head;
String output = "";
while(current != null)
{
output += "[" + current.data + "]";
current = current.next;
}
return output;
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论