给双链表排序(用C语言)为什么不能排序?

来源:百度知道 编辑:UC知道 时间:2024/05/21 22:53:53
#include "stdlib.h"
#include "stdio.h"

typedef
struct node { char data; struct node *front,*next; }
NODE;
int m=0;NODE *head;
NODE *create(int *m);
void print(NODE *head);
insort();
main()
{head=create(&m);
print(head);
}

NODE *create(int *m)
{
NODE *head, *p, *q;
char ch;char a[999];int n=0;

head=(NODE *) malloc(sizeof(NODE));
head->next=NULL;
head->front=NULL;
q=head;
ch=getchar();
while(ch!='\n')
{a[(*m)++]=ch;
ch=getchar();
}
insort();
while(n<*m)
{if(head->next==NULL)
{p=(NODE *) malloc(sizeof(NODE));
p->data=a[n];
q->next=p;
p->front=NULL;
q=p;
}
else
{
p=(NODE *) malloc(sizeof(NODE));
p->data=a[n];
q->next=p;
p->front=q;
q=p;
}
++n;
}<

你那个insort函数只是用来对一个数组排序怎么能说是对双链表排序呢?而且数组还没有初始化。我替你把代码优化了一下并且修改了insort函数。代码如下(用C++写的包含的头文件可能与你的有些不同,你注意一下):
#include <stdlib.h>
#include <stdio.h>
#include <string>

typedef struct node
{
char data;
struct node *front,*next;
}NODE;

int m=0;
NODE *head;
NODE *create(int *m);
void print(NODE *head);
void insort(NODE *head);

int _tmain(int argc, _TCHAR* argv[])
{

head=create(&m);
printf("The original list is:\n");
print(head);
printf("After sorted the list is:\n");
insort(head);
print(head);
}

NODE *create(int *m)
{
NODE *head, *p, *q;
char ch;
char a[999];
int n=0;

printf("Please input a list of chars:\n");
ch=getchar();

while(ch!='\n')
{
a[(*m)++]=ch;
ch=getchar();
}