待完善,如何对链表进行升序排序
#include <stdio.h>
#include <stdlib.h>
typedef struct LINK
{
int data;
struct LINK *next;
}link;
link *appendnode(link *head);
void displynode(link *head);
link *insernode(link *head,int nodedata);
void deletememory(link *head);//释放head指向的链表中的所有节点占用内存
int main()
{
int i=0,nodedata;
char c;
link *head=NULL;
printf("do you want to append a new code(Y/N)?");
scanf(" %c",&c);
while(c=='Y'||c=='y'){
head=appendnode(head);
displynode(head);
printf("do you want to append a new code(Y/N)?");
scanf(" %c",&c);
i++;
}
printf("%d new node have been appended!\n",i);
printf("what is the node value to insert?\n");
scanf("%d",&nodedata);
head=insernode(head,nodedata);//单向链表插入操作
displynode(head);
deletememory(head);
return 0;
}
link *appendnode(link *head){
link *p=NULL,*pr=head;
int data;
p=(link *)malloc(sizeof(link));
if(p==NULL){
printf("no enough memory to allocate!\n");
exit(0);
}
if(head==NULL){
head=p;
}else{
while(pr->next!=NULL){
pr=pr->next;
}
pr->next=p;
}
printf("input node data:");
scanf("%d",&data);
p->data=data;
p->next=NULL;
return head;
}
void displynode(link *head){
link *pr=head;
int j=1;
while(pr!=NULL){
printf("%5d%10d\n",j,pr->data);
pr=pr->next;
j++;
}
}
void deletememory(link *head){
link *p=head,*pr=head;
while(p!=NULL){
pr=p;
p=p->next;
free(pr);
}
}
link *insernode(link *head,int nodedata){
link *p=head,*pr=head,*temp=NULL;
p=(link *)malloc(sizeof(link));
if(p==NULL){
printf("no enough memory!");
exit(0);
}
p->data=nodedata;
p->next=NULL;
if(head==NULL){
head=p;
}else{
while(pr->data<nodedata && pr->next!=NULL){
temp=pr;
pr=pr->next;
}
if(pr->data>=nodedata){
if(pr==head){
p->next=head;
head=p;
}else{
pr=temp;
p->next=pr->next;
pr->next=p;
}
}else{
pr->next=p;//比原链表所有节点值都大,插在最后面
}
}
return head;
}