I am practicing my data structures and trying out this problem on HackerRank on printing the element of a linked list in reverse order.
I have looked through my solutions multiple times but I don't understand why it is wrong.
My Solution:
static void reversePrint(SinglyLinkedListNode head) {
if (head==null){
return;
}
ArrayList<Integer> intList = new ArrayList<>();
while(head!=null){
intList.add(head.data);
head = head.next;
}
Collections.sort(intList, Collections.reverseOrder());
for(int i: intList){
System.out.println(i);
}
}
Appreciate if someone can assist on pointing out my mistakes.
Use Stack
rather than ArrayList
static void reversePrint(SinglyLinkedListNode head) {
if (head==null){
return;
}
Deque<Object> intList = new ArrayDeque<>();
while(head!=null){
intList.push(head.data);
head = head.next;
}
while(!intList.isEmpty()){
System.out.println(intList.pop());
}
}
Appreciate if someone can assist on pointing out my mistakes
The Problem
You used an ArrayList
whose behavior is F irst I n F irst O ut , so the order of the elements printed when you for
-loop the intList
is the same as the order in the linked list, starting from head
.
Possible solutions
To fix your approach, you could simply:
1- Insert each element always in the position zero of intList
using List#add(int index, E element) :
// ...
intList.add(0, head.data);
// ...
2- Or, you can replace the data structure you used to "revert" the elements.
For example, you can use any of the L ast I n F irst O ut data structures, such as Queue
or Deque
in their LIFO variant.
Another alternative
Giving you another completely different solution, you could implement it in a recursive manner like this:
static void reversePrint(SinglyLinkedListNode head) {
if (head != null) {
reversePrint(head.next);
System.out.println(head.data);
}
}
If head
is null
, do not print anything. Otherwise, first reversePrint
the next
element and after that, the current one ( head.data
)... this will cause the reversal effect.
It's worth noting that this doesn't reverse the order of elements, that is, it doesn't modify the next
of each element.
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.