Rutuparna Damle
Rutuparna Damle

Reputation: 15

How to find the maximum element from the linked list?

This is what I have tried so far.

#include<stdlib.h>

struct node
{
  int data;
  struct node *next;
};

void create(struct node **q)
{
  struct node *r,*t;
  int cnt,i,dat;
  printf("How many nodes?");
  scanf("%d",&cnt);
  for(i=0;i<cnt;i++)
    {
       printf("Enter the data %d  ",i);
       scanf("%d",&dat);
       r=(struct node *) malloc (sizeof(struct node));
       r->data=dat;
       r->next=NULL;

       if(*q==NULL)
       {
         *q=r;
       }
      else
       {
         t=*q;
         while(t->next!=NULL)
           {
             t=t->next;
           }
         t->next=r;
       }
    }
}

void display(struct node **q)
{
  struct node *r;
  r=*q;
  while(r!=NULL)
    {
      printf("%d->",r->data);
      r=r->next;
    }
  printf("\n");
}

void max(struct node **q)
{
  struct node *r;
  int max=0;
  r=*q;
  while((r->next)!=NULL)
    {
       max=r->data;
       r=r->next;
       if((r->data)>max)
       {
         max=r->data;
       }
    }
  printf("The max is %d",max);  
  printf("\n");
}

int main()
{
  struct node *head;
  create(&head);
  display(&head);
  max(&head);
}

If I use the numbers 1, 2, and 3 as input my program currently incorrectly detects 2 as the maximum element. How can I fix it so that it will correctly determine 3 to be the maximum element?

rutuparna@pucsd-rutuparna:~/C/Datastructures assignment$ gcc linkedmax.c
rutuparna@pucsd-rutuparna:~/C/Datastructures assignment$ ./a.out
How many nodes?3
Enter the data 0  3
Enter the data 1  2
Enter the data 2  1
3->2->1->
The max is 2

Upvotes: 1

Views: 21724

Answers (1)

simonc
simonc

Reputation: 42175

There are a few issues with the loop

while((r->next)!=NULL) {
    max=r->data;
    r=r->next;
    if((r->data)>max) {
        max=r->data;
    }
}

The line max=r->data unconditionally updates max. Combining this with the fact that the test (r->next)!=NULL causes your loop to exit one item early, the loop currently always returns the value of the second last item.

The code should be changed to something like

while(r!=NULL) {
    if(r->data>max) {
        max=r->data;
    }
    r=r->next;
}

Upvotes: 2

Related Questions