简体   繁体   English

在堆栈数据结构上存储新元素时,.next如何工作? 【JAVA]

[英]How does .next work when storing a new element on the stack data structure? [Java]

I'm learning to implement a Stack and I'm struggling to understand what .next REALLY means. 我正在学习实现堆栈,并且正在努力了解.next的真正含义。 I've seen it in many data structures and it's obvious what its purpose is until I actually ask myself if it is a keyword or how it functions. 我已经在许多数据结构中看到了它,很明显,它的目的是什么,直到我真正问自己这是否是一个关键字或它是如何工作的。 It looks like it is an object but it seems to be acting like a pointer (like in a LinkedList) to each of the item objects that are created. 看起来它是一个对象,但它的行为就像是指向创建的每个item对象的指针(如LinkedList中的指针)。

Please help in any way you can to shed some light on my confusion! 请以任何方式帮助您了解我的困惑!

class Item {
    intdata;
    Item next;

    public Item(int data) {
        this.data = data;
    }
}

public class Stack {

   private Item top;

   public void push(int data) {
       if (null == top) {
           top = new Item(data);
       } else {
           Item item = new Item(data);
           item.next = top;
           top = item;
       }
   }
}

Just think about this, if you have two initial raw data 1 and 2 . 如果您有两个初始原始数据1和2 ,请考虑一下。 And, on the other hand, I tell you to map all the natural numbers as Item s and then put them into a stack. 而且,另一方面,我告诉您将所有自然数映射为Item ,然后将其放入堆栈中。

Considering, you might just come up with let us say, two Item objects currently unrelated as - 考虑一下,您可能只想出两个当前不相关的Item对象,它们是-

Item item1 = new Item(1);

and

Item item2 = new Item(2);

and then as you put them into the Stack , you push item1 and you would eventually push item2 . 然后将它们放入Stack ,您推入item1 ,最终将推入item2 There could similarly be N number of data that you might have pushed. 类似地,您可能已经推送了N个数据。

And now to make you a little smarter, I would ask you to remember while you pop an element from that Stack as to what could be the next element possible, just to see if we might even need to pop more or not from that stack. 现在,为了使您更聪明,我想请您记住从Stack pop一个元素时可能出现的next元素,只是看看我们是否需要从该堆栈中弹出更多元素。 [Let's say need be to display only elements greater than 5] [假设需要仅显示大于5的元素]

That is where the relation between the two items would become useful. 这就是两个项目之间的关系将变得有用的地方。 You make one item point to the next while pushing them into the stack to keep a reference of the same. 您将一个项目指向下一个项目,同时将它们推入堆栈以保持相同的引用。 And so you do:- 所以你这样做:

item2.setNext(item1); // using setter for 'next'

Which eventually means while accessing item2 you can actually be aware of the next Item it points to ie item1 . 这最终意味着在访问item2您实际上可以知道它指向的下一个Item ,即item1

PS : The same implementation as item2.setNext(item1) is generalized in your code's push method which accepts a data and creates a new instance of Item every time its called. PS :与item2.setNext(item1)相同的实现在代码的push方法中得到了概括,该方法接受数据并在每次调用时创建Item的新实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM