Create a new stack in which to put every third element of the first stack
Hello!
I need some help.
I have to do the following task:
Create a stack with numbers in the range from -50 to +50. After creating the stack, perform the following actions: create a new stack, in which every third element of the first stack will be placed. Upon completion, all stacks must be removed.
I was able to write the code of the program with creating a stack in the specified range, viewing and deleting it, but I can not implement the function to create the second stack.
Code:
#include "stdafx.h"
#include <iomanip>
#include <stack>
#include <iostream>
#include <ctime>
using namespace std;
struct Stack
{
int info;
int in;
Stack *next;
} *begin1, *second;
Stack* InStack(Stack*, int);
void View(Stack*);
Stack* DelStackAll(Stack*);
int main()
{ srand(time(0));
int i;
for(i=1; i<=10; i++)
{
begin1=InStack(begin1, rand()%101-50);
}
View(begin1);
begin1=DelStackAll(begin1);
getchar();
}
Stack* InStack(Stack *p, int in){
Stack *t=new Stack;
t->info=in;
t->next=p;
return t;
}
void View(Stack *p)
{
Stack *t=p;
while (t!=NULL)
{
cout<<setw(5)<<t->info;
t=t->next;
}
cout<<endl;
}
Stack* DelStackAll(Stack *p)
{ Stack *t;
while(p != NULL) {
t=p;
p=p->next;
delete t;
}
return p;
}
I will be very grateful for the help!
Re: Create a new stack in which to put every third element of the first stack
- you need to first initialise begin1 and second to nullptr as currently the first time begin1 is passed to InStack it's value is undefined.
- iterate the stack begin1 and for every third entry (keep a counter of the number of entries in the iteration and if % 3 (mod 3) is 0 then you have a third entry) then just call InStack(second, n) where n is the value from the iteration of begin1. This will create the stack second. Then just use View(second) to display the second stack etc.
Re: Create a new stack in which to put every third element of the first stack
Ok, thank you,I understood what I need to do, but there may be another way to do this operation without a counter, since I need to write this function without using what you described.