Table 2-- set of linear and cross training

Problem Description

Here Insert Picture Description

Problem-solving ideas

Involves traversing the list, query, insert, delete and other basic operations

Code

  • List definitions:
typedef char ElemType;
typedef struct Node
{
	ElemType data;
	struct Node* next;
}Node,*LinkList;
  • Create a list
bool CreateList(char* name,LinkList &L)
{
	L = (LinkList)malloc(sizeof(Node));
	L->next = nullptr;
	Node* p = L;
	int i = 0;
	while (true) 
	{
		if (name[i] == '\0')
		{
			break;
		}
		Node* newNode = (LinkList)malloc(sizeof(Node));
		newNode-> data = name[i];
		i++;
		p->next = newNode;
		p = newNode;
		p->next = nullptr;
	}
	return true;
}
  • Find the list
bool Compare(ElemType a, ElemType b)
{
	return a == b;
}
bool SearchList(LinkList& a, ElemType n, bool(*Compare)(ElemType, ElemType))
{
	Node* p = a->next;
	for (; p != nullptr; p = p->next)
	{
		if (Compare(p->data, n))
			return true;
	}
	return false;
}
  • Insert chain (tail plug)
//尾插法
void InsertList(LinkList& a,ElemType n)
{
	Node* p = a->next;
	while (p->next!= nullptr)
	{
		p = p->next;
	}
	Node* newNode = (LinkList)malloc(sizeof(Node));
	newNode->data = n;
	p->next = newNode;
	newNode->next = nullptr;
}
  • Delete list
void DeleteList(LinkList& a,ElemType n)
{
	Node* p = a;
	while (p!= nullptr)
	{
		if (p->next->data == n)
			break;
		p = p->next;
	}
	if (p == nullptr) return;
	Node* q = p->next;
	p->next = q->next;
	free(q);
}
  • Output list
void showList(const LinkList& L)
{
	Node* p = L->next;
	for (; p != nullptr; p = p->next)
	{
		cout << p->data;
	}
	cout << endl;
}
  • Collection and operations
void ListOr(LinkList& a, LinkList& b)
{
	Node* p = b->next;
	for (; p != nullptr; p = p->next)
	{
		if (!SearchList(a, p->data, Compare))
		{
			InsertList(a, p->data);
		}
	}
	showList(a);
}
  • AC operation set
void ListAnd(LinkList& a, LinkList& b)
{
	Node* p = a->next;
	while (p != nullptr)
	{
		if (!SearchList(b, p->data, Compare))
		{
			Node* tmp = p->next;
			DeleteList(a, p->data);
			p = tmp;
		}
		else
		{
			p = p->next;
		}
	}
	showList(a);
}
  • Set difference operation
void ListSub(LinkList& a, LinkList& b)
{
	Node* p = b->next;
	while (p != nullptr)
	{
		if (SearchList(a, p->data, Compare))
		{
			Node* tmp = p->next;
			DeleteList(a, p->data);
			p = tmp;
		}
		else
		{
			InsertList(a, p->data);
			p = p->next;
		}
	}
	showList(a);
}
  • The main function test
int main()
{
	char A[100] = "";
	char B[100]="";
	cin.getline(A,100);
	cin.getline(B,100);
	LinkList la;
	LinkList lb;
	LinkList la1;
	LinkList lb1;
	LinkList la2;
	LinkList lb2;
	CreateList(A, la);
	CreateList(B, lb);
	CreateList(A, la1);
	CreateList(A, la2);
	CreateList(B, lb1);
	CreateList(B, lb2);
	ListAnd(la, lb);
	ListOr(la1, lb1);
	ListSub(la2, lb2);
	return 0;
}
Published 33 original articles · won praise 3 · Views 601

Guess you like

Origin blog.csdn.net/qq_43647628/article/details/104683689
Recommended