簡體   English   中英

如果我只能訪問一個元素和他的下一個元素,我該如何反轉元素列表?

[英]How can I inverse a list of elements if I can only access to an element and his next one?

我得到了一個名為 LinkedList 的“類”,它只有一個屬性“Node first”,它指的是列表的第一個元素。 訪問其他的方法是 class “節點”可以訪問元素“x”和他的下一個:

 public class LinkedList<T> { private static class Node<E> { E elem; Node<E> next; Node (E elem) { this.elem = elem; this.next = null; } } private Node<T> first;

因此,我被命令從 class“LinkedList”執行一個名為“reverse”的方法,該方法必須反轉列表。 然而,練習的難點在於我只能重新鏈接屬性“first”,我的意思是我不能創建輔助數據結構和那種類型的幫助。

我這樣做是為了獲得列表的最后一個元素,但我不知道如何繼續:

 public void reverse () { Node<T> aux = first.next; while (aux.next.= null) { first.elem = aux;elem. aux = aux;next. } first.elem = aux;elem; }

對我來說這似乎是一個理論問題,所以您可能想先檢查 Geek for Geeks。 編程課程中使用的大多數這些問題在那里都有很好的解釋,包括編碼示例。

在這種情況下,一個眾所周知的解決方案是使用三個指針:當前數、上一個數和下一個數; 跟蹤節點以更新反向鏈接。 在這里查看: https://www.geeksforgeeks.org/reverse-a-linked-list/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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