[英]how to get a node by its position in the list in java? (not the value, the whole node)
我有一个链表和一个节点的位置,我需要从列表中获取节点本身(不仅仅是它的值)。 java中是否有一个函数可以做到这一点? 如果没有,你能发送一段代码吗?
谢谢。
public class Node {
public int data;
public Node next;
public Node(int _data) {
this.data = _data;
this.next = null;
}
public String toString() {
return (Integer.toString(data));
}
}
public class LinkedList {
public static void main(String args[]) {
LinkedList linkedlist = new LinkedList();
linkedlist.InsertNode(15);
linkedlist.InsertNode(20);
linkedlist.InsertNode(25);
linkedlist.InsertNode(30);
linkedlist.InsertNode(35);
linkedlist.showLinkedList();
System.out.println("\n");
Node retnode = linkedlist.retPosNode(2);
System.out.println("REturn Node: "+retnode.data);
linkedlist.showLinkedList();
}
Node head;
public void InsertNode(int data) {
Node node = new Node(data);
if (head == null) {
head = node;
} else {
Node n = head;
while (n.next != null) {
n = n.next;
}
n.next = node;
}
}
public Node retPosNode(int pos) {
Node curr = head;
Node prev= null;
Node retPos= null;
int i=0;
if (curr==null)
return null;
while(curr!=null) {
if(i==pos) {
if(i!=0) {
retPos = curr;
prev.next= curr.next;
curr = curr.next;
}
else {
retPos = curr;
head= curr.next;
curr = curr.next;
}
}
prev= curr;
curr = curr.next;
i++;
}
return retPos;
}
public void showLinkedList() {
Node node = head;
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
}
不可以。Java 的LinkedList
不允许您直接在节点上工作。
如果你需要一个 O(1) 的“指针”,你可以使用list.listIterator()
: list.listIterator()
如果您的链表是自定义实现,我 99% 确定这是您的功课,您应该自己做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.