简体   繁体   English

从头到尾遍历LinkedList

[英]Traversing a LinkedList tail to head

I need to traverse through this custom linked list implementation and display its contents: 我需要遍历此自定义链表实现并显示其内容:

  • from head to tail, 从头到尾
  • then again from tail to head. 然后再次从尾到头。

I was able to display the lists contents from head to tail pretty easily with a for loop: 我可以使用for循环轻松地从头到尾显示列表内容:

        for (AccountRecordSerializable account : list) {
            System.out.println(account); 
        }

and everything works fine. 一切正常。 Now I am trying to reverse that. 现在,我试图扭转这种状况。 In provided LinkedList class to use which has a LinkedListIterator class inside it as well. 在提供的LinkedList类中使用,其中也有一个LinkedListIterator类。 The iterator class has methods such as hasNext() , hasPrevious() which I know can be used to do so, but I'm not quite sure how to use that iterator through my LinkedList to do so. 我知道迭代器类具有hasNext()hasPrevious()这样的方法,但是我不太确定如何在LinkedList中使用该迭代器。

Is there a simpler way as I had done before to reverse this? 有没有像我以前做过的更简单的方法可以扭转这种情况? Or how would I use the Iterator class to iterate through my list so that it performs the task? 或者,我将如何使用Iterator类遍历列表以执行任务?

I apologize if this doesn't make any sense... let me know if you need clarifications..Thanks. 如果这没有任何意义,我深表歉意。如果您需要澄清,请告诉我。。谢谢。

A singly linked list is not meant to traverse from tail to head.There are couple of options you have 单链接列表并不意味着要从尾到头遍历。您有几种选择

  1. Reverse the linked list and traverse from head to tail (which will be tail to head for the original linked list) 反转链表并从头到尾遍历(原始链表的头到尾)
  2. Have a stack. 有一个堆栈。 Traverse the linked list and put the elements in the stack. 遍历链接列表并将元素放入堆栈中。 Then keep popping the elements from the stack and print. 然后继续从堆栈中弹出元素并进行打印。

The Java LinkedList implements interface Deque that provides method descendingIterator . Java LinkedList实现了接口Deque ,该接口提供了方法DescendingIterator

Returns an iterator over the elements in this deque in reverse sequential order. 以相反的顺序返回此双端队列中的元素的迭代器。 The elements will be returned in order from last (tail) to first (head). 元素将按从最后(尾)到第一个(头)的顺序返回。

My advise for you is to implement that interfaces in your class, and the obtain reversed iterator. 我的建议是在您的类中实现该接口,并获取反向迭代器。

The linked list is data structure with some properties that you should use to get the implementation. 链表是具有一些属性的数据结构,您应该使用这些属性来获得实现。 The typical construction of linked list is that an element points to next one. 链表的典型构造是一个元素指向下一个。 In your case you have implementation that supports double linked list. 在您的情况下,您具有支持双链表的实现。

private int size = 0; // size can never be < 0
private DLNode<E> head;
private DLNode<E> tail;

In your code you have DLNode that stand for Double Linked Node. 在您的代码中,您有DLNode代表双链接节点。 This means that you can move from head to tail by using hasNex() and from tail to head using hasPrevious() . 这意味着你可以从移动headtail采用hasNex()和尾部使用头hasPrevious()

In your class you have the class LinkedListIterator , that you can obtain with this method: 在您的类中,可以使用以下方法获取类LinkedListIterator

 public ListIterator<E> listIterator(int index) {
    if ((index < 0) || (index > size)) {
        throw new IndexOutOfBoundsException("index " + index+ " is out of range: 0 to " + size);
    }
    return new LinkedListIterator<E>(index);
}

So to print your elements you could do it like this. 因此,要打印您的元素,您可以这样做。

 public <T> void printLinkedListFromHead(LinkedList<T> list) {

   for(ListIterator<T> iterator = list.listIterator(0); iterator.hasNext();) {
       System.out.println(iterator.next());
   }

 }

You should also create a separate class for your code, where you will put your code that contextually does not belong to the linked list implementation. 您还应该为您的代码创建一个单独的类,在该类中您将放置上下文不属于链表实现的代码。 The method readObjects and writeObjects do not belong to class. 方法readObjectswriteObjects不属于类。 same as main. 与main相同。


If you would have standard Java LinkedList you could wrote something like this: 如果您拥有标准的Java LinkedList,则可以编写如下内容:

public <T> reversePrint(Deque deque) {

 for (Iterator<T> iterator = deque.descendingIterator(); iterator .hasNext();){
      System.out.println(iterator .next());
    }
}

To narrow the scope of iterator promote for loop than while. 为了缩小迭代器的范围,可以促进for循环。

I've decided just to traverse backwards by assinging a cursor to the end of the list and iterating through with a get(index) which is then decremented. 我决定通过向后移动游标,将游标指向​​列表的末尾并使用get(index)进行迭代,然后将其递减。 This is what I have: 这就是我所拥有的:

        System.out.println("Tail to Head");
        for (int i = list.size - 1; list.get(i) != null; i--) {
                System.out.println(list.get(i));
                if (i == 0 ){
                    break;
                }
            }

I'm sure there are prettier ways to write it, but it fulfills its purpose for now. 我敢肯定有更漂亮的方法可以编写它,但是现在它已经达到了目的。

Using .descendingIterator() will do what you want :) 使用.descendingIterator()将完成您想要的事情:)

Example: 例:

LinkedList<Integer> linkedList = new LinkedList<Integer>();
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);


Iterator<Integer> iterator = linkedList.descendingIterator();
while (iterator.hasNext())
{
    System.out.println(iterator.next());
}

If you want to save a new LinkedList reversed.. just 如果要保存一个新的LinkedList,则反转。

LinkedList<Integer> linkedList = new LinkedList<Integer>();
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);


Iterator<Integer> iterator = linkedList.descendingIterator();
LinkedList<Integer> reversed = new LinkedList<Integer>();
while (iterator.hasNext())
{
    reversed.add(iterator.next());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM