如何在C中的链接栈中进行Peek操作?

dgtucam1  于 2022-12-02  发布在  其他
关注(0)|答案(1)|浏览(119)

新手来了!
我想在我的程序中再增加一个函数,栈中的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 SYSTEM\n");
    printline();
    printf(" [1] - PUSH");
    printf("\n [2] - POP");
    printf("\n [3] - PEEK");
    printf("\n [4] - DISPLAY");
    printf("\n [0] - EXIT\n");
    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 DISPLAY\n");
        printline();
    }
    else
    {
        while(top!=NULL)
        {
             printline();
             printf("\t STUDENT MANGAMENT SYSTEM\n");
             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");
}
ru9i0ody

ru9i0ody1#

复制pop函数中的代码,但删除top=top-〉next;

相关问题