0
#include<stdio.h>
#include<stdlib.h>
//structure//
struct node
{
    int data;
    struct node *link;
};
//function to push elements into stack//
void push(struct node *top_ref,int x)
{
    struct node *new=(struct node *)malloc(sizeof(struct node));
    new->data=x;
    new->link=top_ref;
    top_ref=new;
}
//function to get largest element//
int largest(struct node *top_ref)
{
    int temp=0;
    while(top_ref!=NULL)
    {
        if(temp<top_ref->data)
        {
            temp=top_ref->data; 
        }
        top_ref=top_ref->link;
    }
    return temp;
}
//function to print the stack//
void print(struct node *top_ref)
{
    while(top_ref!=NULL)
    {
        printf("%d->",top_ref->data);
        top_ref=top_ref->link;
    }
    printf("\n");
}
//main function//
int main()
{
    struct node *stack=(struct node *)malloc(sizeof(struct node));
    stack=NULL;
    push(stack,1);
    push(stack,5);
    push(stack,6);
    push(stack,3);
    print(stack);
    printf("the largest no. is %d\n",largest(stack));
}

trying to find the largest no. in a stack. there is a problem in line 20, 32 top_ref->data is not being accesed top_ref is the last node of the linked list new to linked list and data structures

the output i am getting is

empty line
the largest no. is 0

Paweł Tomkiel
  • 1,974
  • 2
  • 21
  • 39

1 Answers1

0

The point here is stack is a pointer to another pointer so should be taken as a double pointer in push function.

#include<stdio.h>
#include<stdlib.h>
//structure//
struct node
{
    int data;
    struct node *link;
};
//function to push elements into stack//
void push(struct node **top_ref,int x)
{   
    struct node * tmp=(struct node *)malloc(sizeof(struct node));
    tmp->data=x;
    tmp->link=NULL;
    if(top_ref==NULL){
        *top_ref=tmp;
    }
    else{
        tmp->link= *top_ref;
        *top_ref=tmp;   
    }
 }
//function to get largest element//
    int largest(struct node *top_ref)
    {
        int temp=0;
        while(top_ref!=NULL)
        {
        if(temp<top_ref->data)
        {
        temp=top_ref->data; 
        }
        top_ref=top_ref->link;
        }
        return temp;
        }
//function to print the stack//
    void print(struct node *top_ref)
    {
        while(top_ref!=NULL)
    {
        printf("%d->",top_ref->data);
        top_ref=top_ref->link;
    }
        printf("\n");
    }
//main function//
    int main()
    {
        struct node *stack;
        stack=NULL;
        //stack=NULL;
        push(&stack,1);
        push(&stack,5);
        push(&stack,6);
        push(&stack,3);
        print(stack);
        printf("the largest no. is %d\n",largest(stack));
    }
Aadil Ahmad
  • 139
  • 9