您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验3(最近就写这玩意了)

2008-11-01 18:23 302 查看
输入任意多个,任意长度的单词,按字母顺序排序输出

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#define BASE_SIZE 5
int x=BASE_SIZE;
//本程序的功能是,输入nCount个单词,知道输入了#为止,然后按照他们的名字的字母顺序排序
struct Node
{
char *ch;
Node *pNext;
};

Node *create()
{
int yy;
char * word();
void print(char *name[],int n);
void sort(char *n[],int k);
char **p;//二级指针
char *str;
void sort(char *n[]);
Node *pHead = NULL;
Node *pPrevious = NULL;
Node *pNew = NULL;
int nCount = 0;
do
{
pNew = (Node *)malloc(sizeof(Node));
printf("请输入单词:");
pNew->ch=word();
printf("/n");
pNew->pNext = NULL;
nCount++;
if (NULL == pHead)
{
pHead = pNew;
}
if (NULL == pPrevious)
{
pPrevious = pNew;
}
pPrevious->pNext = pNew;
pPrevious = pNew;

}while('#'!=*(pNew->ch));
nCount--;
printf("你输入了%d个单词/n",nCount);
printf("它们是:/n");
p=new char*[nCount];//动态创立指针数组
pPrevious=pHead;
for(int i=0;i<nCount;i++)//把链表中的字符串放到指针数组里
{
p[i]=pPrevious->ch;
pPrevious=pPrevious->pNext;
}
sort(p,nCount); //排序
print(p,nCount);//输出排序后的单词
system("pause");
return pHead;
}

void sort(char *name[],int n)//排序字母的函数
{
char *temp;
int i,j,k;
for(i=0;i<n-1;i++)
{
k=i;
for(j=i+1;j<n;j++)
if(strcmp(name[k],name[j])>0)k=j;
if(k!=i)
{temp=name[i];name[i]=name[k];name[k]=temp;}
}
}

void print(char *name[],int n)//输出的函数
{
int i;
for(i=0;i<n;i++)printf("%s/n",name[i]);
}

char * word()
{
char *str;
int n=0;
char c;
str=new char[BASE_SIZE];
while(c!=13)
{
c=getche();
str
=c;
n++;
if(n>x-2)
{
str=(char *)realloc(str,x+BASE_SIZE);
x+=BASE_SIZE;
}
}
str
='/0';
return str;
}

void main()
{
printf("请输入您要排序的单词,直到输入'#'结束/n");
create();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: