带有链表的c中的堆栈-将元素与头部错误中的元素进行比较
Posted
技术标签:
【中文标题】带有链表的c中的堆栈-将元素与头部错误中的元素进行比较【英文标题】:stack in c with linked list - comparing an element with element in head error 【发布时间】:2021-05-19 10:35:06 【问题描述】:我正在尝试实现一个应用程序,该应用程序使用单链接列表使用一堆employee
结构,其中每个员工都由他/她的增值税号、姓名和工资来描述。
我正在尝试扩展代码,以便当用户选择“1”时,它将从控制台读取新员工的数据,检查他的薪水是否高于堆栈顶部员工的薪水,并打印比较结果。
新元素在栈中的push正常,但是if
检查salary是否高于栈顶salary却不起作用。
同样,我想知道要添加什么,以便用户可以点击“3”来打印堆栈中每个唯一员工的数据。
#include <stdio.h>
#include <stdlib.h>
struct employee
int am;
char name[50];
float salary;
struct employee *next;
;
void init(struct employee **head);
void show(struct employee *head);
int push(struct employee s, struct employee **head);
int pop(struct employee *s, struct employee **head);
int main()
struct employee data;
struct employee *head;
int ch;
init(&head);
do
printf("\nMenu ");
printf("\n1.Push ");
printf("\n2.Pop ");
printf("\n3.Show contents ");
printf("\n0.Exit ");
printf("\nChoice: ");
scanf("%d",&ch);
switch (ch)
case 1:
printf("Enter employee data:");
scanf("%d %s %f", &data.am, data.name, &data.salary);
if (push(data,&head))
printf("Successfully pushed to stack.\n");
printf("%f\n", data.next->salary);
if (data.salary > head->salary)
printf("salary on the head is bigger\n");
else
printf("salary on the head is less\n");
else
printf("No memory available, push failed.\n");
break;
case 2:
if (pop(&data,&head))
printf("Popped: %d %s %.1f\n",data.am, data.name, data.salary);
else
printf("Empty stack, no data retrieved.\n");
break;
case 3:
show(head);
break;
case 0:
printf("Bye!\n");
break;
default:
printf("Try again.\n");
break;
while (ch!=0);
exit(0);
void init(struct employee **head)
*head = NULL;
int push(struct employee d, struct employee **head)
int done=0;
struct employee *s;
s = (struct employee *)malloc(sizeof(struct employee));
if (s!=NULL)
*s = d;
s->next = *head;
*head = s;
done = 1;
return done;
int pop(struct employee *s, struct employee **head)
int done=0;
struct employee *temp;
if (*head != NULL)
temp = *head;
*s = **head;
*head = (*head)->next;
free(temp);
done = 1;
return done;
void show(struct employee *head)
struct employee *i;
printf("--- Top of stack ---\n");
for (i=head; i!=NULL; i=i->next) //maybe here edit for the odd positions
printf("%d %s %.2f\n",i->am,i->name,i->salary);
printf("---Bottom of stack---\n");
【问题讨论】:
【参考方案1】:对于您的第一个问题,您将数据推送到堆栈顶部(因此您的 data
成为负责人),然后检查与负责人的工资差异。否则,你是在和自己比较。
您可能希望在推入堆栈之前检查,或将if
行替换为
if (head->salary > data.next->salary)
请注意,在检查其薪水之前,您还需要检查next
节点是否存在。
【讨论】:
以上是关于带有链表的c中的堆栈-将元素与头部错误中的元素进行比较的主要内容,如果未能解决你的问题,请参考以下文章