有序單鏈表的(交、並、差)運算
阿新 • • 發佈:2019-01-14
head node 運算 struct sizeof typedef 算法 一個 根據
#include "stdafx.h" #include "malloc.h" typedef struct Node { char data; Node *next; }List;
// 創建單鏈表 void CreateList(List *&L, char a[], int n) { List *s,*r; L = (List *)malloc(sizeof(List)); L->next = NULL; r = L; for (int i = 0; i < n; i++) { s = (List *)malloc(sizeof(List)); s->data = a[i]; r->next = s; r = s; } r->next = NULL; }
// 使用了排序算法中的插入排序 void Sort(List *&head) { List *p = head->next, *q, *r; // p指向第一個節點 if(p!=NULL) { r = p->next; // r指向第二個節點 p->next = NULL; // p的後繼節點為NULL p = r; // p指向第一個節點 while (p!=NULL) { r = p->next; q = head; while (q->next!=NULL &&q->next->data<p->data) { q = q->next; } p->next = q->next; q->next = p; p = r; } } } // 求兩個集合並集 void Union(List *La, List *Lb, List *&Lc) { List *la = La->next, *lb = Lb->next,*tc,*s; Lc = (List *)malloc(sizeof(List)); tc = Lc; // 在進行比較 if (la != NULL && lb != NULL) { while (la != NULL && lb != NULL) { s = (List *)malloc(sizeof(List)); if (la->data > lb->data) { // la節點大於lb節點 s->data = lb->data; tc->next = s; tc = s; lb = lb->next; } else if(la->data<lb->data) { // la節點小於lb節點 s->data = la->data; tc->next = s; tc = s; la = la->next; } else { s->data = la->data; tc->next = s; tc = s; la = la->next; lb = lb->next; } } } // 剩余節點(la與lb必定有一個是NULL) if (lb != NULL) { la = lb; } while (la!=NULL) { s = (List *)malloc(sizeof(List)); s->data = la->data; tc->next = s; tc = s; la = la->next; } tc->next = NULL; } // 求兩個集合的並集 void InterSect(List *La, List *Lb, List *&Lc) { List *la = La->next, *lb,*tc, *s; Lc = (List *)malloc(sizeof(List)); tc = Lc; while (la!=NULL) { lb = Lb->next; // 根據鏈表為有序鏈表過濾一部分比較節點 while (lb!=NULL && lb->data<la->data) { lb = lb->next; } if (lb != NULL && lb->data == la->data) { s = (List *)malloc(sizeof(List)); s->data = la->data; tc->next = s; tc = s; } la = la->next; } tc->next = NULL; } // 求差集,即a-b,去掉a鏈表中與b鏈表的交集 void Subs(List *La, List *Lb, List *&Lc) { List *la = La->next, *lb, *tc, *s; Lc = (List *)malloc(sizeof(List)); tc = Lc; while (la!=NULL) { lb = Lb->next; // 根據鏈表為有序鏈表過濾一部分比較節點 while (lb!=NULL && lb->data<la->data) { lb = lb->next; } // 去掉Lb鏈表與La鏈表的交集部分 if (!(lb != NULL &&la->data == lb->data)) { s = (List *)malloc(sizeof(List)); s->data = la->data; tc->next = s; tc = s; } la = la->next; } tc->next = NULL; }
1、使用單鏈表對集合進行交、並、差的運算,重點在於對單鏈表進行排序,排序後的單鏈表在進行運算,可以減少節點的比較優化時間復雜度。
有序單鏈表的(交、並、差)運算