2
#include <stdio.h>
#include <stdlib.h>
typedef struct pilhaElement{
int data;
struct pilhaElement *next;
}PilhaElment;
typedef struct pilha{
PilhaElment *head;
PilhaElment *tail;
int size;
}Pilha;
Pilha *iniciarpilha(){
Pilha *pi = (Pilha *) malloc(sizeof(Pilha));
if(pi!=NULL){
pi->size = 0;
pi->head = NULL;
pi->tail = NULL;
}
return pi;
}
void liberapilha(Pilha *pi){
if(pi != NULL){
PilhaElment *node;
while(pi->head!=NULL){
node = pi->head;
pi->head = pi->head->next;
free(node);
}
free(pi);
}
}
void push(Pilha *pi,int num){
if(pi == NULL){
return;
}
PilhaElment *node = (PilhaElment *) malloc(sizeof(PilhaElment));
if(pi->size == 0){
node->data = num;
node->next = NULL;
pi->head = node;
pi->tail = node;
}
else{
node->data = num;
node->next = NULL;
pi->tail->next = node;
pi->tail = node;
}
(pi->size)++;
}
void printpilha(Pilha *pi){
if(pi == NULL){
printf("Pilha vazia.\n");
return;
}
PilhaElment *node = pi->head;
while(node != NULL){
printf("%d ",node->data);
node = node->next;
}
}
void pop(Pilha *pi){
if(pi == NULL){
printf("Pilha vazia.\n");
}
PilhaElment *node = pi->head;
while(node!=pi->tail){
node = node->next;
}
node->next = NULL;
free();
}
int main(){
Pilha *pi = iniciarpilha();
push(pi,1);
push(pi,2);
push(pi,3);
printpilha(pi);
pop(pi);
printf("\n%d",pi->tail->data);
//printpilha(pi);
return 0;
}
Someone gives me help to solve the problem of the pop function, she should be removing at the end, but I’m breaking the dick when I try, the insertion of the stack is being at the end.
Is there a way to [Dit] the question and explain the problem better? If you are implementing a stack, it makes no sense for you to remove an element from the end, since it is LIFO (last in, first out).
– Woss
Yes, I know it’s LIFO, so I’m inserting at the end. That’s why I’m removing at the end.
– Pedro Henrique Faria Teixeira
In fact, I must have misunderstood. The [Edit] tip the question remains. Explain what each function should do and what each one is doing, as well as the logic you tried to implement in the ones that are not working.
– Woss
@Andersoncarloswoss , if @Pedrohenriquefariateixeira put the new elements at the end, then it makes sense to remove from the end. @Pedrohenriquefariateixeira , as you are using list on, I would give the
push
and thepop
in the header (head
in its code) of the stack; I prefer to do this manipulation of the stack at the end of it when the implement over an array– Jefferson Quesado