简体   繁体   English

我将如何从单链列表中的特定节点返回数据?

[英]How would I go about returning the data from a specific node in a singly linked list?

Do I have to search for the node as a stack or queue, and when I find it set the data that the node returns equal to local variables? 我是否必须将节点搜索为堆栈或队列,并且在找到节点时将节点返回的数据设置为等于局部变量?

Or is there a way of calling a known position in the list, like how you can with an array. 或者有没有一种方法可以调用列表中的已知位置,例如如何使用数组。

Visually what I'm asking here is: 视觉上我在这里问的是:

So how Arrays work like this: 因此, 数组的工作方式如下:

ArrayofStrings[Postion] returns String located at Position

Is there a way to do the same with a Linked List like this? 有没有办法对像这样的链表做同样的事情?

SinglyLinkedList(Node) returns Multiple(string) Data(double) 

I'm guessing I have to search the list for the node, but I wanted to make sure there wasn't an easier way to do this. 我猜想我必须在列表中搜索该节点,但是我想确保没有更简单的方法可以做到这一点。

java中的所有列表都提供get的实现,该实现返回list中的第n个元素。

LinkedLists pros and cons LinkedList的优缺点

pros 优点

  • traversing 遍历
  • adding or removing anywhere because you just have to change two pointers(reference in Java) 在任何地方添加或删除,因为您只需要更改两个指针(Java中的引用)

cons 缺点

  • get by index because it will traverse through elements until it finds the specific one (doubly linked list may be a little faster because if you have total count you can start from beginning or end depending on the index ie if there are 100 elements and you want to goto 75 you can start from the other end which will only require to traverse 25 elements) 按索引获取,因为它将遍历元素,直到找到特定的元素(双向链表可能会更快一些,因为如果您拥有总数,则可以从开始或结束开始,具体取决于索引,即如果有100个元素,并且您想要转到75,您可以从另一端开始,只需要遍历25个元素)

Arrays pros and cons. 数组的优缺点。

pros 优点

  • traversing (even subset), 遍历(偶数子集),
  • adding data at the end 最后添加数据
  • getting element from a specific location. 从特定位置获取元素。

cons 缺点

  • If you add or remove element from the middle it will shift all the elements after that location. 如果您从中间添加或删除元素,它将在该位置之后移动所有元素。

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

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