关于c++请教高手

试编写数组为a[]={1,2,5,5,6,7,7,7,9}的带表头结点单链表中统计出值为x的元素个数的函数,统计结果由函数值返回。

要求手动输入一个值就输出该值在数组中的个数。

#include <stdio.h>
#include <stdlib.h>
/*
试编写数组为a[]={1,2,5,5,6,7,7,7,9}的带表头结点单链表中统计出值为x的元素个数的函数,
统计结果由函数值返回。
要求手动输入一个值就输出该值在数组中的个数
*/
/*定义NODE结点*/
typedef struct _Node{
int iValue;
_Node * pNext;
}NODE, *PNODE;

/*定义头结点(全局)*/
PNODE pHead;

/*创建题目中的链表*/
void CreateList(void)
{
int a[] = {1,2,5,5,6,7,7,7,9};
PNODE pNewNode = NULL;
PNODE pWork = NULL;

pHead = (PNODE)malloc(sizeof(NODE));
if ( NULL == pHead )
{ /*生成头结点*/
printf("创建链表时发生错误!\n");
exit(-1);
}
pHead->iValue = 0;
pHead->pNext = NULL;
pWork = pHead;

for ( int i = 0 ; i < 9 ; i++ )
{
pNewNode = (PNODE)malloc(sizeof(NODE));
if ( NULL == pNewNode )
{
printf("创建链表时发生错误!\n");
exit(-1);
}
/*用尾插法生成单链表*/
pNewNode->iValue = a[i];
pNewNode->pNext = NULL;
pWork->pNext = pNewNode;
pWork = pNewNode;
}
}

/*销毁生成的链表*/
void DestroyList(void)
{
PNODE pWork = pHead->pNext;
free(pHead);
while( pWork != NULL )
{ /*从链表头部开始删除所有结点*/
pHead = pWork;
pWork = pWork->pNext;
free(pHead);
}
}

/*统计链表中值为X的元素个数*/
int CountNum(void)
{
int X = 0;
int iCounted = 0;
PNODE pWork = pHead->pNext;

printf("Enter X = ");
scanf("%d",&X);

while ( pWork != NULL )
{
if ( pWork->iValue == X )
{
iCounted++;
}
pWork = pWork->pNext;
}
return iCounted;
}

int main(void)
{
int iNum = 0;
CreateList();
iNum = CountNum();
printf("count result: [%d]\n",iNum);
DestroyList();/*链表用完了一定要删除*/

fflush(stdin);
getchar();
return 0;
}
温馨提示:答案为网友推荐,仅供参考
相似回答