单链表表的合并(C语言描述)

```language #include #define OK 1 #define ERROR 0 typedef int ElemType; typedef int Status; // 定义单链表 typedef struct LNode { ElemType data; struct LNode *next; }*LinkList; //初始化单链表 Status InitList(LinkList &L) { L = new LNode; L->next = NULL; return OK; } //尾插法创建单链表 void CreateList(LinkList &L, int n) { LinkList p,mei; L = new LNode; L->next = NULL; mei = L; for (int i = 1; i <= n; ++i) { p = new LNode; printf("请输入第%d个元素: ", i); scanf_s("%d", &p->data); p->next = NULL; mei->next = p; mei = mei->next; } } //根据下标查找元素 Status GetElem(LinkList L, int i, ElemType &e) { LinkList p; int j = 1; p = L->next; while (p && j < i) { p = p->next; ++j; } if (!p || j > i) { //printf("下标%d元素没有找到\n", i); return ERROR; } e = p->data; //printf("下标%d的元素是%d\n", i, e); return e; } //根据给定元素查单链表 Status LocateElem(LinkList L, ElemType e) { LinkList p; p = L->next; int j = 1; while (p && p->data != e) { p = p->next; ++j; } if (!p) { //printf("没有找到元素%d\n", e); return ERROR; } //printf("元素%d的下标是%d\n", e, j); return OK; } //尾插法 Status ListInsert(LinkList &L, ElemType e) { LinkList p; p = L; int j = 0; while (p->next != NULL ) { p = p->next; //++j; } LinkList s; s = new LNode; s->data = e; s->next = NULL; p->next = s; return OK; } //链表合并 void Union(LinkList &LA, LinkList &LB, int n, int m) { int e, a; for (int i = 1; i <= n; i++) { e = GetElem(LB, i, e); a = LocateElem(LA, e); if (a != 1) ListInsert(LA, e); } } //打印单链表 void PrintList(LinkList L) { LinkList p; p = L->next; while (p) { printf("%d ", p->data); p = p->next; } printf("\n"); } int main() { int m, n, e = 888; LinkList LA, LB; InitList(LA); InitList(LB); printf("请输入LA元素个数m: "); scanf_s("%d", &m); CreateList(LA, m); PrintList(LA); printf("请输入LB元素个数n: "); scanf_s("%d", &n); CreateList(LB, n); PrintList(LB); Union(LA, LB, n, m); PrintList(LA); } ``` 运行结果如下所示: ![image.png](http://www.icode9.com/i/li/?n=2&i=images/20210618/1624020553789728.png?,size_14,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=)
上一篇:两个链表合并


下一篇:13.java接口