【C++】数据结构之统计单链表中结点的值等于给定值X的结点数目

// 单链表统计数相同结点数目.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
const int SIZE = 10;

//结点
typedef struct node
{
	int data;
	struct node *next;
}node,*LinkNode;

//初始化数组
void InitArr(int *arr)
{
	srand(time(0));
	for (int i = 1; i <= SIZE; i++)
	{
		arr[i] = rand() % (10 - 1 + 1) + 1;
	}
}

//初始化结点
int InitNode(LinkNode link)
{
	if (link = new node())
	{
		link->next = NULL;
		return 1;
	}
	else
	{
		return 0;
	}
}

//创建链表
int CreatLink(LinkNode link,int *arr)
{
	if (!link)
		return 0;
	node *q=link;
	for (int i = 1; i <= SIZE; i++)
	{
		node *p = new node();
		p->data = arr[i];
		q->next = p;
		q = p;
	}
	return 1;
}

//统计统计单链表中结点的值等于给定值X的结点数目
int CountX(LinkNode link,int e)
{
	int cnt = 0;
	node *p=link->next;
	while (p)
	{
		if (p->data == e)
			cnt++;
		p = p->next;
	}
	return cnt;
}

//输出数组
void OutArr(int *arr)
{
	for (int i = 1; i <= SIZE; i++)
	{
		cout << arr[i] << '\t';
	}
	cout << endl;
}

int main()
{
	node link;//定义表头
	int arr[SIZE + 1];//定义数组
	InitArr(arr);//初始化数组
	OutArr(arr);//输出数组
	if (InitNode(&link))
	{
		CreatLink(&link, arr);//创建链表
		cout << CountX(&link, 8) << endl;//输出链表中结点值和元素8相等的结点个数。
	}
}


你可能感兴趣的:(C++)