【发布时间】:2014-03-19 01:59:56
【问题描述】:
对于预实验(意味着它不是为了成绩),我应该使用链表实现我的第一个堆栈。我写它时只在堆栈中添加了一件东西,就像练习一样,为什么它这么短。无论如何,我没有编译错误,除了它说“new”在我的 create_stack 函数中未初始化。这也是我遇到分段错误的地方,因为它没有打印出我的第一个 printf 函数。我也猜测问题不仅仅是我初始化堆栈,但这是我的问题的开始。如果事情很简单,请放轻松,就像我说的,这是我第一次做堆栈,感谢您的帮助。
#include <stdio.h>
#include <stdlib.h>
typedef struct node_{
char data;
struct node_ *next;
}node;
typedef struct stack_{
unsigned int size;
node* stack;
}stack;
stack* create_stack();
void push(stack* s, char val);
char top(stack* s);
void pop(stack*s);
int main(void) {
char value, val;
stack* new = create_stack();
printf("Enter a letter: ");
scanf("%c", &value);
push(new, value);
val = top(new);
printf("%c\n", val);
pop(new);
return 0;
}
stack* create_stack(){ //initializes the stack
stack* new;
new->size = 0;
new->stack = NULL;
return new;
}
void push(stack* s, char val) {
node* temp = (node*)malloc(sizeof(node)); //allocates
if ( temp == NULL ) {
printf("Unable to allocate memory\n");
}
else{
temp->next = s->stack;
temp->data = val;
s->stack = temp;
s->size = (s->size) + 1; //bumps the counter for how many elements are in the stack
}
}
void pop(stack* s) {
node* temp;
temp = s->stack;
s->stack = temp->next;
free(temp);
s->size = (s->size) - 1; //subtracts from counter
}
char top(stack* s) {
node* temp = s->stack;
char value = temp->data;
return value;
}
【问题讨论】:
标签: c linked-list stack