亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何通過節點在java列表中的位置獲取節點?

如何通過節點在java列表中的位置獲取節點?

蠱毒傳說 2022-05-25 17:20:59
我有一個鏈表和一個節點的位置,我需要從列表中獲取節點本身(不僅僅是它的值)。java中是否有一個函數可以做到這一點?如果沒有,你能發送一段代碼嗎?
查看完整描述

2 回答

?
繁星淼淼

TA貢獻1775條經驗 獲得超11個贊

不,JavaLinkedList不允許您直接在節點上工作。

如果你需要一個 O(1) 的“指針”,你可以使用 ListIterator:list.listIterator()

如果你的鏈表是一個自定義實現,我 99% 肯定這是你的作業,你應該自己做。


查看完整回答
反對 回復 2022-05-25
?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

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;

        }

    }   

}


查看完整回答
反對 回復 2022-05-25
  • 2 回答
  • 0 關注
  • 112 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號