C++ realizes the chain representation of linear table

1. Related concepts of linked list

1. Related nouns

Insert picture description here
Insert picture description here
Insert picture description here

2. The characteristics of the linked list

Insert picture description here
Insert picture description here

3. Linked list classification

Insert picture description here

4. Representation of singly linked list

Insert picture description here
Insert picture description here

Insert picture description here

Second, the C++ implementation of singly linked list

typedef struct
{
    
    
	string name;
	int age;
}Student; //定义结点的数据域 

typedef struct LNode
{
    
    
	Student data;  //结点的数据域 
	LNode* next; //结点的指针域 
}LNode, *LinkList; //定义结点 

int InitList(LinkList &L) //链表的初始化 
{
    
    
	L = new LNode();  //让头指针指向头结点 
	L->next = NULL;
	return 1;
}

int IsEmpty(LinkList L)  //判断链表是否为空 
{
    
    
	return L->next==NULL?1:0;
} 

int DestoryList(LinkList &L) //销毁链表 
{
    
    
	LinkList p = L;
	while(L)
	{
    
    
		p = L;
		L = L->next;
		delete p;
	}
	return 1;
}

int ClearList(LinkList &L) //清空链表 
{
    
    
	LinkList p = L->next;
	LinkList q;
	while(p)
	{
    
    
		q = p->next;
		delete p;
		p = q;
	}
	L->next = NULL;
	return 1;
} 

int ListLength(LinkList L) //获得链表的长度 
{
    
    
	LinkList p = L->next;
	int i = 0;
	while(p)
	{
    
    
		i++;
		p = p->next;
	}
	return i;
} 

int GetLNode(LinkList L, int i, Student& s) //获取链表中第i个元素的数据域 
{
    
    
	int j = 1;
	LinkList p = L->next;
	while(p&&j<i)
	{
    
    
		p = p->next;
		j++;
	}
	if(!p||j>i)
	{
    
    
		return 0;
	}
	s = p->data;
	return 1;
}

LNode *FindLNode(LinkList L, Student s) //查找指定元素并返回其地址 
{
    
    
	LinkList p = L->next;
	while(p&&(p->data.age!=s.age||p->data.name!=s.name))
	{
    
    
		p = p->next;
	}
	return p;
}

int InsertLNode(LinkList &L, int i, Student s) //将数据s插入到链表的第i个位置 
{
    
    
	LinkList p = L;
	int j = 0;
	while(p&&j<i-1)
	{
    
    
		p = p->next;
		j++;
	}
	if(!p||j>i-1)
	{
    
    
		return 0;
	}
	LinkList q = new LNode();
	q->data = s;
	q->next = p->next;
	p->next = q;
}

int DeleteLNode(LinkList &L, int i) //删除链表中的第i个结点 
{
    
    
	LinkList p = L;
	int j = 0;
	while(p->next&&j<i-1)  //找到第i-1个结点 
	{
    
    
		p = p->next;
		j++;
	}
	if(!(p->next)||j>i-1)
	{
    
    
		return 0;
	} 
	LinkList q = p->next;
	p->next = q->next;
	delete q;
	return 1;
}

void CreatList1(LinkList& L, int n) //头插法创建含有n个结点的链表 
{
    
    
	InitList(L);
	LinkList p;
	for(int i=0; i<n; ++i)
	{
    
    
		p = new LNode();
		cin >> p->data.age;
		cin >> p->data.name;
		p->next = L->next;
		L->next = p;
	}
}

void CreatList2(LinkList& L, int n) //尾插法创建含有n个结点的链表 
{
    
    
	InitList(L);
	LinkList p, q = L;
	for(int i=0; i<n; ++i)
	{
    
    
		p = new LNode();
		cin >> p->data.age;
		cin >> p->data.name;
		p->next = NULL;
		q->next = p;
		q = p;
	}
}

Guess you like

Origin blog.csdn.net/qq_46027243/article/details/113802674