简体   繁体   中英

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

I have been given a "class" called LinkedList which has only one atributte "Node first" which refers to the first element of a list. The way to access the other ones is that class "Node" has access to an element 'x' and his following one:

 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;

So that, I have been ordered to do a method called "reverse" from class "LinkedList" which has to reverse the list. However, the difficulty of the exercise is that I can only re-link the attributte "first", I mean I cannot create auxiliar data structures and that type of help.

I have done this in order to achieve the last element of the list, but I dont know how to continue:

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

It seems quite a theoretical question to me, so you might want to check Geek for Geeks first. Most of these questions that are used in programming courses are well explained there, including coding examples.

In this case, a well-known solution is to use three pointers: a current number, the previous number, and the next number; to keep track of nodes to update reverse links. Check here: https://www.geeksforgeeks.org/reverse-a-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