C语言 我使用链表(没有数组)创建了一个堆栈,但我的 pop 函数不起作用



在我的pop函数中,我将head的地址存储在temp中,然后继续前进。当我在temp中遇到死胡同时,我通过为其分配NULL来删除它。但是,当我打印堆栈时,它不会删除最后一次推送。

我试过使用temp->next=NULL.只有这样它才在工作,但如果temp->next=NULL在工作。temp=NULL不应该也工作吗?

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
struct student
{
char name[20];
int id;
double cgpa;
struct student* next;
} *head;
void print()
{
struct student* temp = head;
while(temp != NULL)
{
printf("id %d name %s cgpa %lfn", temp->id, temp->name, temp->cgpa);
temp = temp->next;
}
}
void push(struct student* temp)
{
if(head == NULL)
{
head = temp;
return;
}
struct student* current = head;
while(current->next != NULL)
{
current = current->next;
}
current->next=temp;
}
void pop()
{
struct student* temp = head;
if(head == NULL)
{
printf("n no element to popn");
}
else
{
while(temp->next != NULL)
{
temp = temp->next;
}
temp = NULL;
}
}
int main()
{
char operation;
struct student* temp = NULL;
head = NULL;
while(1)
{
// a for ADD, r for POP, s for print
scanf("%c", &operation);
if(operation == 'a')
{
temp = (struct student*)malloc(sizeof(struct student));
scanf("%d %s %lf", &temp->id, &temp->name, &temp->cgpa);
temp->next = NULL;
push(temp);
}
else if(operation == 'r')
{
pop();
}
else if(operation == 's')
{
print();
}
}
}

a
1 joy 2.3
a
5 boy 3.3
s
r
s

预期结果应为:

1 joy 2.3
5 boy 3.3
1 joy 2.3

但实际结果是

1 joy 2.3
5 boy 3.3
1 joy 2.3
5 boy 3.3

该函数更改局部变量temp,而不是更改列表最后一个节点之前节点的数据成员next

它可以看起来像这样

void pop()
{
if ( head == NULL )
{
printf("n no element to popn");
}
else
{
struct student **temp = &head;
while ( ( *temp )->next != NULL )
{
temp = &( *temp )->next;
}
free( *temp );
*temp = NULL;
}
}

现在,变量temp正好指向最后一个节点之前节点的数据成员next。那就是列表本身发生了变化。

不要忘记释放最后一个节点。

代码temp=NULL将变量temp设置为 null,而不是temp的字段next。对于后者,它实际上并没有删除节点。

你的权利是流行音乐不起作用。 您只需在找到结束元素时将临时指针设置为 NULL。 您需要做的是先在 temp 释放元素,然后将指向它的指针从上一个元素设置为 NULL。

void pop()
{
if(head==NULL){
printf("n no element to popn");
}
else
{
struct student* temp=head;
struct student* previous=head;
while(temp->next!=null){
previous=temp;
temp=temp->next;
}
if(previous!=next) //if there was more than one
{
previous->next=NULL;
}
else
{
head=NULL;
}
free(temp);

}
}

最新更新