0
The first element of the stack
How can i change the first element of a stack? Please, give me some advices
6 Respuestas
+ 1
Hello Hakan Nihat
In which language?
And what are you trying to do. Can you give an example?
+ 1
Unfortunately I am not familiar with c++.
But I think you have to use another stack to store the elements above the first element.
your stack:
4
3
2
1
2
3
1 4
stack a stack b
Now you can change the first element in stack a. After that you can put the other elements from stack b back to stack a.
0
``` #include <iostream>
using namespace std;
struct elem
{int key; elem *next;} *start=NULL,*temp=NULL;
elem *push(elem **st, int n);
elem *pop (elem **st, int &n);
void init (elem **st);
int empty (elem **st);
void main ()
{int nov;
init (&start);
int num;
cout<<"Input a value:\n";
while (cin>>num)
start=push(&start, num);
while (start->next==NULL)
{ temp=pop(&start,num);
cout<<num<<" ";}
cout<<endl;
cout<<"stoinost za possledniq element: ";
cin>>nov;
start->key=nov;
while(!(temp->next==NULL))
start=pop(&temp,num);
}
void init (elem **st)
{st=NULL;}
int empty(elem **st)
{
if (st==NULL)
return 1;
else
return 0;
}
elem *push (elem **st, int n)
{
elem *p;
p=new elem;
p->key=n;
p->next=*st;
*st=p;
return p;
}
elem *pop( elem **st, int &n)
{
elem *p;
n=(*st)->key;
p=*st;
*st=(*st)->next;
delete p;
return *st;}
```
0
C++. I have to reach to the last element and change it without losing previous ones
0
Yes, but how can i change it. That's my problem.
0
If you use pop() it returns the value, right?
To catch this value you should use a variable.
In pseudo code
int a = stackA.pop();
while(!stackA.isEmpty())
stackB.push(a);
a = stackA.pop();
end loop
now you can change a:
a = yourNumber;
put this back to stackA:
stackA.push(a);
refill stackA:
while(!stackB.isEmpty())
a = stackB.pop();
stackA.push(a);
end loop
But I am not sure if this is the best way. ;)