rewrite your code
- function
init
delete as it will create nodes that are not used. - Changed to the node between the maximum and minimum values since it is sufficient to simply replace the value.
like this
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int num;
struct node *next;
} NODE;
NODE* add(NODE **head, NODE **tail, int x){
NODE *temp;
temp = (NODE*)malloc(sizeof(NODE));
temp->num = x;
if(*head == NULL){
temp->next = temp;
*tail = *head = temp;
} else {
temp->next = *head;
(*tail)->next = temp;
*tail = temp;
}
return *head;
}
void print(NODE *p){
NODE *top =p;
do{
printf("%d ", p->num);
p=p->next;
}while(p != top);
printf("\n");
}
void drop(NODE *head, NODE *tail){
NODE *p = head;
tail->next = NULL;
while(p){
NODE *temp = p;
p = p->next;
free(temp);
}
}
void minmax(NODE *head, NODE *tail){
NODE *p, *maxp, *minp;
int temp;
maxp = minp = p = head;
do{
if(maxp->num < p->num){
maxp = p;
}
if(minp->num > p->num){
minp = p;
}
p = p->next;
}while(p != head);
temp = maxp->num; maxp->num = tail->num; tail->num = temp;
if(tail == minp)//exchanged minp
minp = maxp;//fixed
temp = minp->num; minp->num = head->num; head->num = temp;
}
int main(void){
int i, x;
NODE *head, *tail;
tail = head = NULL;
for(i=0;i<7;i++){
printf("%d>", i+1);
scanf("%d", &x);
add(&head, &tail, x);
}
//print(head);
minmax(head, tail);
print(head);
drop(head, tail);
return 0;
}