C++連結串列類的簡單操作含圖書結構體 簡單易懂

充滿鮮花的世界到底在哪裡發表於2018-01-13
//#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <cstring>
#include <ctime>

using namespace std;

class Random_Chinese
{
public:
	string Rand_Chinese()
	{
		srand(unsigned(clock() * (time(NULL))));                    //產生毫秒隨機數(利用clock函式將時間轉換為毫秒單位)  
		Sleep(1);                                                   //試試註釋一下你就懂了  

		rand1 = 0xf7 - 0xb0;
		rand2 = 0xfe - 0xa1;

		byte1 = rand() % rand1 + 0xb0;
		byte2 = rand() % rand2 + 0xa1;

		str = byte1;
		str += byte2;

		return str;                                                 //返回隨機漢字   
	}

private:
	string str;
	BYTE byte1, byte2;
	int rand1;
	int rand2;
};

class List
{
public:
	List() : head(new Book), bp1(NULL), bp2(NULL) { head->next = NULL; }
	~List();
	void output_list();
	void input_list();
	void find_list();

private:
	struct Book
	{
		int num_book;
		string name_book;
		struct Book *next;
	};
	Book *head, *bp1, *bp2;
	Random_Chinese r_c;
	static int i;
	static string temp_s;
};

int List::i = 0;

List::~List()
{
	if (NULL == head->next)
	{
		delete head;
		return;
	}
	while (head)										//連結串列的銷燬
	{
		bp1 = head->next;
		delete head;
		head = bp1;
	}
}

void List::output_list()
{
	bp1 = head;
	cout << "所有書目如下:" << endl;
	while (bp1->next)
	{
		bp1 = bp1->next;

		cout << bp1->num_book << "\t" << bp1->name_book << endl;
	}
}

void List::input_list()
{
	bp1 = head;
	for (i = 0; i < 10; i++)									//設定圖書書目
	{
		bp1->next = new Book;
		bp1 = bp1->next;

		bp1->num_book = i;
		bp1->name_book = r_c.Rand_Chinese() + r_c.Rand_Chinese();
	}
	bp1->next = NULL;
}

void List::find_list()
{
	bp1 = head;
	cout << "請輸入您要查詢圖書的編號:";
	cin >> i;
	while (bp1->next)
	{
		bp1 = bp1->next;
		if (i == bp1->num_book)
		{
			cout << bp1->name_book << endl;
			return;
		}
		else if (NULL == bp1->next)
			cout << "經查詢無此書" << endl;
	}
}

int main()
{
	List list;
	list.input_list();
	list.output_list();
	list.find_list();

	cout << endl;
	system("pause");
	return 0;
}

相關文章