[英]How to implement push on a linked list
I am looking for help implementing push stack on this linked list.我正在寻找帮助在这个链表上实现推送堆栈。 Some tips would be appreciated :)
一些提示将不胜感激:)
The program runs properly, I am just looking how to add a push statement程序运行正常,我只是在看如何添加push语句
import java.util.Scanner;
public class StackList {
LinkedListBasic stackList = new LinkedListBasic();
// Adds new elements to the top of the stack
public void push(int data){
}
public static void main(String[] args){
StackList newStackList = new StackList();
Scanner input = new Scanner(System.in);
while(true){
int data = input.nextInt();
if(data == -1) break;
newStackList.push(data);
}
public class Node{
int data;
Node next;
public Node(int data){
this.data = data;
next = null;
}
}
To push a new element onto the top of the linked list, you must have access to the head (first element) of the linked list and do three things:要将新元素推送到链表的顶部,您必须能够访问链表的头部(第一个元素)并执行三件事:
next
field to the head of the linked listnext
字段设置为链表的头部Assuming you are maintaining a head node.假设您正在维护一个头节点。
public void push(int data) {
if(head == null) {
Node node = new Node(data);
head = node;
}else {
Node node = new Node(data);
node.next = head;
head = node;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.