数据结构题型4-按值查找

#include   //引入头文件
using namespace std;

typedef int Elemtype;

#define Maxsize 100
#define ERROR 0
#define OK    1

typedef struct LNode
{
	Elemtype data;//数据域
	struct LNode* next;//指针域
}LNode, * LinkList;

bool InitList(LinkList& L)   //初始化
{
	L = (LinkList)malloc(sizeof(LNode));
	if (L == NULL)
		return ERROR;
	L->data = 0;
	L->next = NULL;
	return OK;
}

bool ListEmpty(LinkList L)  //判断是否为空
{
	if (L->next != NULL)
	{
		cout << "not empty" << endl;
		return OK;
	}
	else
	{
		cout << "empty,只有头节点" << endl;
		return ERROR;
	}
}

int ListLength(LinkList L)
{
	LNode* p;
	p = L->next;
	int i = 0;
	while (p != NULL)
	{
		p = p->next;
		i++;
	}
	return i;
}

LinkList List_HeadInsert(LinkList& L)  //头插法
{
	L = (LinkList)malloc(sizeof(LNode));
	L->data = 0;
	L->next = NULL;
	LNode* s = NULL;
	int x = 0;
	while (cin >> x)
	{
		s = (LinkList)malloc(sizeof(LNode));
		s->data = x;
		s->next = L->next;
		L->next = s;
		if (cin.get() == '\n') break;
	}
	return L;
}

LinkList List_TailInsert(LinkList& L)  //尾插法
{
	L = (LinkList)malloc(sizeof(LNode));
	L->data = 0;
	L->next = NULL;
	LNode* s = NULL, * r = NULL;
	r = L;
	int x = 0;
	while (cin >> x)
	{
		s = (LinkList)malloc(sizeof(LNode));
		s->data = x;
		r->next = s;
		r = s;
		if (cin.get() == '\n') break;
	}
	s->next = NULL;
	return L;
}
LNode* GetElem(LinkList L, int i)
{
	if (i < 0) return NULL;
	int j = 0;
	LNode* p = L;
	while (p && j < i)
	{
		p = p->next;
		j++;
	}
	return p;
}
//------------------------核心代码------------------------//
LNode* LocateElem(LinkList L, int e)
{
	LNode* p = L->next;
	while (p && p->data != e)
	{
		p = p->next;
	}
	return p;
}
//------------------------核心代码------------------------//
int main(void)
{
	LinkList L;
	InitList(L);//不加入的话,会提示报错,L没有进行初始化。
	List_TailInsert(L);  //尾插法
	if (LocateElem(L, 3) != NULL)
	{
		cout << "LocateElem=" << LocateElem(L, 3)->data << endl;
	}
	else
		cout <<"Locate fail !!!" << endl;
	cout << L << " " << L->data << " " << L->next << endl;
	cout << L->next << " " << L->next->data << " " << L->next->next << endl;
	cout << L->next->next << " " << L->next->next->data << " " << L->next->next->next << endl;
	cout << L->next->next->next << " " << L->next->next->next->data << " " << L->next->next->next->next << endl;
	ListEmpty(L);
	cout << "length=" << ListLength(L) << endl;;
	return 0;
}

数据结构题型4-按值查找_第1张图片
数据结构题型4-按值查找_第2张图片

你可能感兴趣的:(算法与数据结构,数据结构)