猿问

如何通过节点在java列表中的位置获取节点?

我有一个链表和一个节点的位置,我需要从列表中获取节点本身(不仅仅是它的值)。java中是否有一个函数可以做到这一点?如果没有,你能发送一段代码吗?



蛊毒传说
浏览 100回答 2
2回答

繁星淼淼

不,JavaLinkedList不允许您直接在节点上工作。如果你需要一个 O(1) 的“指针”,你可以使用 ListIterator:list.listIterator()如果你的链表是一个自定义实现,我 99% 肯定这是你的作业,你应该自己做。

慕无忌1623718

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;        }    }   }
随时随地看视频慕课网APP

相关分类

Java
我要回答