簡體   English   中英

java - 如何通過其在列表中的位置獲取節點? (不是值,是整個節點)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM