I need to find the maximum number and the minimum number in a circular linked list and i should move the minimum number to the start of the list (before head) and the maximum number to the end of the list (before minimum)
why my code is giving me error in output?
Note: Using doubly linked list is disallowed ,we should do this only with circular linked list.
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int num;
struct node *next;
} NODE;
void init(NODE **h)
{
(*h) = (NODE*)malloc(sizeof(NODE));
(*h)->next = *h;
}
NODE* add(NODE* h,NODE* p,int x)
{
int i;
NODE *temp;
temp = (NODE*)malloc(sizeof(NODE));
temp->num = x;
temp->next = h;
if(h->next == h)
{
h->next = temp;
return h;
}
else
{
temp = p->next;
p = temp;
return h;
}
return h;
}
NODE* fin(NODE *h,NODE *p)
{
NODE* ptr,*pmin,*pmax,*temp,*temp2,*mnprev,*mxprev;
// temp: minimum
// temp2: maximum
// pmin: holds the minimum
// pmax: holds the maximum
// ptr: o(n) search
// mnprev: holds the previous node of the minimum
// mxprev: hold the previous node of the maximum
mnprev = mxprev = pmin = pmax = h;
ptr = h->next;
int mini, maxi;
mini = h->num;
maxi = h->num;
do
{
if(ptr->num < mini)
{
mini = ptr->num;
pmin = ptr;
mnprev->next = pmin;
}
if(ptr->num > maxi)
{
maxi = ptr->num;
pmax = ptr;
mxprev->next = pmax;
}
ptr = ptr->next;
} while(ptr != h);
temp = pmin;
temp2 = pmax;
mnprev->next = pmin->next;
mxprev->next = pmax->next;
free(pmin);
free(pmax);
temp->next = h;
temp2->next = temp;
ptr = temp;
do {
printf("%d ",ptr->num);
ptr = ptr->next;
} while(ptr != h);
}
int main()
{
int i,x;
NODE *lis,*p;
init(&lis);
p = lis;
for(i=0;i<7;i++)
{
scanf("%d",&x);
add(lis,p,x);
}
fin(lis,p);
}