编写一个c程序,要求用户从键盘输入任意个数字,该程序能从小到大的排序,如果遇到相同的数字就把这个数字删去,并输出结果。比如输入4,6,5,3,输出3 4 5 6.如果输入4,6,5,3,4,输出3 5 6。要求使用动态链表。VC++6.0环境。能成功运行的一定追分。
数据结构体应该也用上
#include<stdio.h>
#define MAX 1024
struct Node
{
int value;
struct Node * next;
};
struct Node* head = NULL;
int GetNextStart(char* st, int last, int len)
{
int i;
for(i=last; i<len; i++)
{
if(st[i]==',')
return i+1;
}
return len+1;
}
void DoWithValue( int value )
{
struct Node * pCur=head, *plast=NULL;
if(head==NULL)
{
//没有节点,直接插入;
pCur = (struct Node *)malloc(sizeof(struct Node));
pCur->value = value;
pCur->next = NULL;
head = pCur;
return;
}
else
{
while(pCur != NULL && value > pCur->value)
{
plast = pCur;
pCur= pCur->next;
}
if(pCur != NULL && value == pCur->value)
{
// 删除
if(plast==NULL)
{
// 删除的是第一个节点
head = pCur->next;
free(pCur);
}
else
{
// 删除的不是第一个节点
plast->next = pCur->next;
free(pCur);
}
}
else
{
// 插入
struct Node * pNew = (struct Node *)malloc(sizeof(struct Node));
pNew->value = value;
if(plast==NULL)
{
// 插入位置是第一个节点
pNew->next = head;
head = pNew;
}
else
{
// 插入位置不是第一个节点
pNew->next = plast->next;
plast->next = pNew;
}
}
}
}
void ShowAllList()
{
struct Node* p = head;
printf("Values of List:\n");
while(p!=NULL)
{
printf("%d ",p->value);
p = p->next;
}
printf("\n");
}
void DelAllList()
{
struct Node* p = head, *plast=NULL;
while(p!=NULL)
{
plast =p;
p = p->next;
free(plast);
}
}
int main()
{
char stInput[MAX],ch;
int i=0,curStart=0,curEnd,nextStart,len;
int value;
printf("Please input a line of numbers, split with [,]:\n");
while((ch=getchar())!='\n')
{
stInput[i++]=ch;
}
stInput[i]='\0';
len = strlen(stInput);
while(curStart<len)
{
nextStart = GetNextStart(stInput, curStart, len);
curEnd = nextStart-1;
stInput[curEnd] = '\0';
value = atoi(stInput+curStart);
DoWithValue(value);
curStart = nextStart;
}
ShowAllList();
DelAllList();
}