简体   繁体   中英

Possible to traverse the singly linked list from tail to head? (Java)

I was wondering if it is possible to traverse singly LinkedList from tail to head with only using the for-loop.

For Example, I can traverse from head to tail with given head.

 LinkedList temp = head;    
   for (int i = 0; i < size-1; i++) {
      temp = temp.getNext();
}

But it is possible to do below code for traversing from tail to head?

 LinkedList temp = tail;    
   for (int i = 0; i < size -1; i++) {
      temp = temp.getNext();
}

Well, the simplest answer is, use doubly linked list if you need to traverse back to head.

However, if you really want to do so with a singly linked list , and if you don't want to use any library, you should implement the class on your own and add a reverse method like this:

public void reverse () {
    Node pointer = head;
    Node previous = null, current = null;
    while (pointer != null) {
        current = pointer;
        pointer = pointer.next;
        current.next = previous;
        previous = current;
        head = current;
    }
}

By this method you can reverse the current singly linked list, so you can traverse from the tail to head of original linked list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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