// 單鏈表統計數相同結點數目.cpp : 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include <vector>
#include <cstring>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>
#include <stdio.h>
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++】數據結構之統計單鏈表中結點的值等於給定值X的結點數目
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.