patterncppMinor
Print element in a linked list in reverse
Viewed 0 times
reverseprintelementlistlinked
Problem
I solved this problem in C++ and was looking for feedback on my code. I'm not sure if storing the data in an array and looping through it in reverse and printing was the right approach since this challenge was to use linked lists, but I didn't know how else to do it:
You are given the pointer to the head node of a linked list and you
need to print all its elements in reverse order from tail to head, one
element per line. The head pointer may be null meaning that the list
is empty - in that case, do not print anything!
You are given the pointer to the head node of a linked list and you
need to print all its elements in reverse order from tail to head, one
element per line. The head pointer may be null meaning that the list
is empty - in that case, do not print anything!
/*
Print elements of a linked list in reverse order as standard output
head pointer could be NULL as well for empty list
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
void ReversePrint(Node *head)
{
// creates nodes named current, prev, next
struct Node *current, *prev, *next;
// sets current and previous to their respective values. current is head because it is starting position while previous is where we want the head to be pointing, which is null, since we are reverse a linked list
current = head;
prev = NULL;
// allocate memory to an array and initialize i=0
int array[100], i=0;
while (current != NULL) {
// store data into an array to print out later
array[i] = current->data;
i+=1;
// updates next [current, link] -> [int, link] = next
next = current->next;
// updates link of current.next to value of previous
current->next = prev;
// updates previous value
prev = current;
// updates current value
current = next;
}
// at the end of list, sets head to the last value in linked list which is previous
head = prev;
// goes through array in reverse order and prints
for(int j=i-1; j>=0; j--) {
cout<<array[j]<<endl;
}
}Solution
This approach is fine if you know the linked list will always be less than 100 elements. To fix this issue while still using the same method, you could iterate through the linked list first to count the number of elements needed in your array.
If I were doing this problem, I'd look at using a stack... just push all the elements onto the stack, then pop them all off again to print them. This way we avoid iterating through the linked list twice (once to count, once to store in an array), while still solving to problem.
If I were doing this problem, I'd look at using a stack... just push all the elements onto the stack, then pop them all off again to print them. This way we avoid iterating through the linked list twice (once to count, once to store in an array), while still solving to problem.
Context
StackExchange Code Review Q#136023, answer score: 2
Revisions (0)
No revisions yet.