我正在尝试将堆栈实现为链接列表。这是我目前的代码:
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
typedef struct node {
int data;
struct node* link;
} Node;
typedef Node* list;
list head;
void push(list top, int item) {
if (head == NULL) {
head = (list) malloc(sizeof(Node));
head->data = item;
head->link = NULL;
top = head;
} else{
list temp = (list) malloc(sizeof(Node));
temp->data = item;
temp->link = top;
top = temp;
}
}
int pop(list top) {
if (top == NULL) {
printf("stack is empty");
/*int tdata=top->data;
top=top->link;
return tdata;*/
} else {
int tdata = top->data;
top = top->link;
return tdata;
}
}
void display(list top){
while (top != NULL) {
printf("%d", top->data);
top = top->link;
}
}
int main() {
int ch, item;
list top;
for (;;) {
printf("1.push\t2.pop\t3.display\t4.exit");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("enter the element to be pushed");
scanf("%d",&item);
push(top,item);
break;
case 2:
item=pop(top);
printf("element popped is: %d",item);
break;
case 3:
display(top);
break;
case 4:
exit(0);
break;
default:
printf("enter valid choice");
}
}
}
当我按下&#39; 2&#39;调用pop
方法,但无论顶部是什么项目,它都会打印消息&#34;弹出的元素是:11&#34;。当我按下&#39; 3&#39;对于display
方法,我得到&#34;分段错误(核心转储)&#34;。为什么会这样?要使此代码有效,需要进行哪些修改?
答案 0 :(得分:1)
我对你的程序进行了一些修改。最重要的是将指针传递给列表头部的函数,函数本身就是一个指针,以便函数可以改变它。
我还删除了全局head
并初始化了本地top
。我在代码中评论了其他事项。
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *link;
} Node; // removed pointer type to Node
void push(Node **top, int item) { // takes address of the pointer
Node *temp= malloc(sizeof(Node)); // do not cast malloc
if(temp == NULL) // check that malloc did work
exit(42);
temp->data = item; // no need for separate clause at first push
temp->link = *top; // link is previous top
*top = temp; // top is new struct, pass it back
}
int pop(Node **top) { // takes address of the pointer
int tdata;
Node *temp;
if (*top == NULL) {
printf("stack is empty\n"); // added newline here and other places
return 0;
}
tdata = (*top)->data; // collect the data
temp = (*top)->link; // remember the next list item
free(*top); // give memory back
*top = temp; // pass new top back to caller
return tdata;
}
void display(Node *top){
while (top != NULL) {
printf("%d ", top->data); // added spacing
top = top->link;
}
printf("\n"); // added newline
}
int main(void) {
int ch, item;
Node *top = NULL; // initialise the list !!
do {
printf("1.push 2.pop 3.display 4.exit ");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("enter the element to be pushed ");
scanf("%d",&item);
push(&top,item); // pass address so pointer can be updated
break;
case 2:
item=pop(&top); // pass address so pointer can be updated
printf("element popped is: %d\n",item);
break;
case 3:
display(top);
break;
case 4:
break;
default:
printf("enter valid choice\n");
}
} while(ch != 4); // changed the loop style
}
答案 1 :(得分:0)
发生的事情是您只是初始化或设置任何值到您的列表指针top
。
请好好看看你的插入函数push
。它会收到指针。如果您想将您的成员top
作为[out]
参数发送到此函数,您应该发送一个指向指针(**
)的指针或指针的引用(*&
)。
像这样发送top
不会修改它的值并留下垃圾,因为这个变量也从未初始化...