微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

名人在 C 语言中使用堆栈

如何解决名人在 C 语言中使用堆栈

对于这个问题,你必须使用一个二维数组或矩阵,并使用 Stack 函数 push 和 pop ,找到矩阵中的名人成员。只用C语言

这是我尝试过的代码

#include <stdio.h>


#define size 4

int stack[size];
int top=-1;

void push(int val){
    if(top==size-1){
        printf("stack is already full,error\n");
    
    }else{
        top++;
        stack[top]=val;
    }
}

int pop(){
    if(top==-1)
    {
        printf("underflow condition");
    }
    else{
        return stack[top--];
    }
}
int CelebrityProblem(int arr[4][4]) 
{ 
    
  int i;
    for ( i = 0; i<4; i++) 
        push(i); 
  
    while (size>1) 
    { 
        int temp1 =stack[top];
        pop();

        int temp2 = stack[top];
        pop();

        if (arr[temp1][temp2]) 
           push(temp2);

        else
           push(temp1);
    } 
    
    int potential_celeb=stack[top];
int j;
    for( j=0; j<4; j++)
    {
        if(j==stack[top])
            continue;
        
        if(arr[potential_celeb][j]==1)
            return -1;
            
        if(arr[j][potential_celeb]!=1)
            return -1;
        
    }
  
    return potential_celeb; 
} 
int main(){
    int arr[4][4]={ {0,1,1},{1,0},{0,0} };
                    
      int celebrity = CelebrityProblem(arr);

    if(celebrity == -1)
        printf("No Celebrity Exists!");
    else
       printf("Celebrity is Person Number %d",celebrity);
    return 0;

}

根据我的方法,我将输出作为 conditionunderflow 。任何人都可以帮我找到我做错的地方。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。