如何做Peek操作,在链接堆栈在C?



新手!

我想在我的程序中添加一个函数,栈中的peek操作,但是我不知道怎么做。当用户选择第三个选项,即peek操作时。我想让程序打印最上面的id号,名字和课程。

我想要的输出,

最上面的ID号为:最上面的名字是:排名第一的课程是:

下面是其他函数的代码。

#include<stdio.h>
#include<malloc.h>
typedef struct info
{
char name[20],courses[50];
int idnum;
struct info *next;
};
struct info *push(struct info *);
struct info *pop(struct info *);
struct info *peek(struct info *);
void display(struct info *);
void printline();
int main()
{
struct info *top=NULL;
int ch;
printline();
printf("t STUDENT MANGAMENT SYSTEMn");
printline();
printf(" [1] - PUSH");
printf("n [2] - POP");
printf("n [3] - PEEK");
printf("n [4] - DISPLAY");
printf("n [0] - EXITn");
printline();
do
{
printf("Enter your choice: ");
scanf("%d",&ch);
printline();
switch(ch)
{
case 1:
top=push(top);
break;
case 2:
top=pop(top);
break;
case 3:
break;
case 4:
display(top);
case 0:
printline();
printf("Thank you nHave a Nice Day!n");
break;
}
}while(ch!=0);
}
struct info *push(struct info *top)
{
struct info *p;
p=(struct info *)malloc(sizeof(struct info));
if(p==NULL)
{
p -> next = NULL;
top = p;
}
else
{
printf("Enter the Student name: ");
scanf("%s",&p->name);
printf("Enter Student course: ");
scanf("%s",&p->courses);
printf("Enter the ID number of Student: ");
scanf("%d",&p->idnum);
p->next=top;
top=p;
}
return(top);
}
struct info *pop(struct info *top)
{
struct info *p;
if(top==NULL)
{
printf("nothing to pop");
}
else
{
printf("nThe Student name is: %s",top->name);
printf("nThe Student course is: %s",top->courses);
printf("nThe ID Number of the student is: %d",top->idnum);
top=top->next;
}
return(top);
}
struct info *peek(struct info *top){
}
void display(struct info *top)
{
if(top==NULL)
{
printf("NOTHING TO DISPLAYn");
printline();
}
else
{
while(top!=NULL)
{
printline();
printf("t STUDENT MANGAMENT SYSTEMn");
printline();
printf("nThe student name is: %s",top->name);
printf("nThe student address is: %s",top->courses);
printf("nThe marks of the student is: %d n",top->idnum);
printline();
top=top->next;
}
}
}
void printline(){
int i;
for(i=0; i<50; i++)
printf("-");
printf("n");
}

复制pop function中的代码,但去掉top=top->next;

相关内容

  • 没有找到相关文章

最新更新