I have a linked list and a position of a node, and I need to get the node itself from the list (not only its value). Is there a func in java that does that? if not, can you send a piece of code that does that?
Thanks.
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;
}
}
}
No. Java's LinkedList
doesn't allow you to work directly on the nodes.
If you need an O(1) “pointer”, you can use a ListIterator: list.listIterator()
If your linked list is a custom implementation, I'm 99% sure it's your homework and you should do it yourself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.