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 }
 
        

實現樣例:

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM