6-10 jmu-ds-有序链表的插入删除 (15 分)

题目要求:

链表L是一个有序的带头结点链表,实现有序链表插入删除操作。

实现函数为:

#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct LNode  		//定义单链表结点类型
{
	ElemType data;
	struct LNode *next;		//指向后继结点
} LNode,*LinkList;
void CreateListR(LinkList &L,int n);//尾插法建链表
void DispList(LinkList L);//输出链表
void DestroyList(LinkList &L);//销毁链表
void ListInsert(LinkList &L,ElemType e);//有序链表插入元素e
void ListDelete(LinkList &L,ElemType e);//链表删除元素e
int main() 
{
	LinkList L,L1,L2;
	int n,e;
	cin>>n;
	CreateListR(L,n);//细节不表。
	cin >> n;
	while (n--)
	{
		cin >> e;
		ListInsert(L, e);
	}
	cout << "插入数据后的链表:";
	DispList(L);
	cout << endl;
	cin >> n;
	while (n--)
	{
		cin >> e;
		ListDelete(L, e);
	}
	cout << "删除数据后的链表:";
	DispList(L);
	DestroyList(L);//销毁链表,细节不表
	return 0;
}
void DispList(LinkList L)
{
	LinkList p;
	int flag=1;
	p=L->next;
	if (L->next == NULL)
	{
		cout << "空链表!";
		return;
	}
	while(p){
		if(flag) {
			cout<<p->data;flag=0;
		}
		else {
			cout<<" "<<p->data;	
		}
		p=p->next;
	}


 1 void ListInsert(LinkList &L, ElemType e) {
 2     LinkList p = new(LNode);
 3     p = L;
 4     LinkList node = new(LNode);
 5     while (1) { 
 6         if (p != nullptr&&p->next!=nullptr) {
 7             if (e >= p->data&&e<=p->next->data) {
 8                 node->data = e;
 9                 node->next = p->next;
10                 p->next = node;
11                 return;
12             }
13             p = p->next;
14         }
15         else
16             break;
17     }
18     node->data = e;
19     p->next = node;
20     p = p->next;
21     p->next = nullptr;
22     return;
23 }
24 void ListDelete(LinkList &L, ElemType e) {
25     LinkList p = new(LNode);
26     p = L;
27     if (p->next == nullptr)
28         return;
29     while (1) { 
30         if (p != nullptr&&p->next != nullptr) {
31             if (e == p->next->data) {
32                 p->next = p->next->next;
33                 return;
34                 }
35         }
36         if (p == nullptr)
37             break;
38         p = p->next;
39     }
40     cout << e << "找不到!" << endl;
41 }
 

实现样例:

猜你喜欢

转载自www.cnblogs.com/haijie-wrangler/p/10596737.html