How to print the entire stack using a single for each?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our W3Make Forum to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
For printing the linked list we have to do the following things :
– Make a void function take take reference of head as a parameter
– Make a Temp Variable of node type and initialize it with head.
– Start a While Loop Until temp-> next = NULL
– In While Print print the data of temp
– Change the Position of temp with temp->next
Here is the Code
void display(node* &head){
node* temp = head;
while(temp->next!=NULL){
cout<data<next;
}
}
I Hope this Was Helpful.
You can use the toArray() method of the Stack class to convert the stack to an array, and then use a single for-each loop to print each element in the array. Here’s an example:
Stack<Integer> stack = new Stack<Integer>();
stack.push(1);
stack.push(2);
stack.push(3);
for (int i : stack.toArray(new Integer[stack.size()])) {
System.out.println(i);
}