满意答案
wo785461261
2013.11.16
采纳率:43% 等级:11
已帮助:4639人
#include
#include
//整数单链表
struct numList
{
int num;
numList* next;
};
//函数原型声明
numList* create(int n);
int add(numList* head, int n);
void sort(numList* head);
void output(numList* head);
void main()
{
char* p;
p=NULL;
int count;
int evenCount = 0; //奇数个数
int oddCount = 0; //偶数个数
numList* list;
numList* evenList;
numList* oddList;
numList* pNode;
printf("输入整数个数及各整数值:\n");
scanf("%d",&count);
list = create(count);
evenList = (numList*)malloc(sizeof(numList));
evenList->next = NULL;
oddList = (numList*)malloc(sizeof(numList));
oddList->next = NULL;
pNode = list->next;
while(pNode != NULL)
{
if((pNode->num & 1) == 0)
{
//如果是偶数
evenCount++;
add(evenList, pNode->num);
}
else
{
//如果是奇数
oddCount++;
add(oddList, pNode->num);
}
pNode = pNode->next;
}
//对偶数和奇数链表排序
sort(evenList);
sort(oddList);
//输出
printf("%d %d\n",evenCount, oddCount);
output(evenList);
output(oddList);
}
/*************************************************
【函数名称】create
【功能】创建一个具有n个节点的单链表
【参数】节点数
【返回值】指向头节点的指针
*************************************************/
numList* create(int n)
{
numList* head;
numList* pCur;
numList* pNext;
head = (numList*)malloc(sizeof(numList));
if(head == NULL)
{
return NULL;
}
head->next = NULL;
pCur = head;
while(n>0)
{
pNext = (numList*)malloc(sizeof(numList));
if(pNext == NULL)
{
return NULL;
}
if(scanf("%d",&pNext->num)==0)
break;
pNext ->next = NULL;
pCur->next = pNext;
pCur = pNext;
n--;
}
return head;
}
/*************************************************
【函数名称】add
【功能】向链表末尾添加一个节点
【参数】指向链表头节点的指针及添加元素的值
【返回值】插入成功返回1,失败则返回0
*************************************************/
int add(numList* head, int n)
{
if(head == NULL)
{
return 0;
}
numList* p;
numList* pNewNode;
p = head;
while(p->next != NULL)
{
//得到尾既节点指针
p = p->next;
}
pNewNode = (numList*)malloc(sizeof(numList));
if(pNewNode == NULL)
{
return 0;
}
pNewNode->num = n;
pNewNode->next = NULL;
p->next = pNewNode;
return 1;
}
/*************************************************
【函数名称】sort
【功能】使用简单选择排序对节点元素升序排列
【参数】指向链表头节点的指针及添加元素的值
【返回值】无
*************************************************/
void sort(numList* head)
{
if(head == NULL)
{
return;
}
int temp;
numList* pStart;
numList* pCur;
for(pStart = head->next; pStart != NULL; pStart = pStart->next)
{
for(pCur = pStart->next; pCur != NULL; pCur = pCur->next)
{
if(pStart->num > pCur->num)
{
temp = pStart->num;
pStart->num = pCur->num;
pCur->num = temp;
}
}
}
}
/*************************************************
【函数名称】output
【功能】输出链表节点元素
【参数】指向链表头节点的指针及添加元素的值
【返回值】无
*************************************************/
void output(numList* head)
{
if(head == NULL)
{
return;
}
numList *p;
p = head->next;
while(p != NULL)
{
printf("%d ",p->num);
p = p->next;
}
printf("\n");
}
00分享举报