8.合并删除一次实现
#include <stdio.h>
#include <stdlib.h>
#define N 5
#define M 8
typedef struct node
{
int data;
struct node * next;
}ElemSN;
ElemSN * Createlink(int a[],int n);//创建带表头单向链表
void Printlink(ElemSN *h);//打印带表头单向链表
ElemSN * fun(ElemSN *h1,ElemSN *h2);//升序
int main()
{
int a[N] = {2,2,4,4,6};
int b[M] = {1,2,2,3,3,4,4,5};
ElemSN *head1,*head2,*head;
//创建带表头单向链表
head1 = Createlink(a,5);
head2 = Createlink(b,8);
//打印原链表
printf("原链表1为:");
Printlink(head1);
printf("\n");
printf("原链表2为:");
Printlink(head2);
printf("\n");
//升序
printf("升序结果为:");
head = fun(head1,head2);
free(head2);
Printlink(head);
printf("\n");
return 0;
}
//创建带表头单向链表
ElemSN * Createlink(int a[],int n)
{
ElemSN *h,*t,*p;
h = (ElemSN *)malloc(sizeof(ElemSN));
t = h;
for(int i = 0;i < n;i++)
{
p = (ElemSN *)malloc(sizeof(ElemSN));
p->data = a[i];
p->next = NULL;
t->next = p;
t = p;
}
return h;
}
//打印链表
void Printlink(ElemSN *h)
{
ElemSN *p;
for(p = h;p->next;p = p->next)
{
printf("%d ",p->next->data);
}
}
//升序
ElemSN * fun(ElemSN *h1,ElemSN *h2)
{
ElemSN *s,*p,*t,*h;
h = NULL;
while(h1->next && h2->next)
{
if(h1->next->data < h2->next->data)
{
p = h1->next;
h1->next = p->next;
}
else
{
p = h2->next;
h2->next = p->next;
}
p->next = NULL;
if(!h)
{
t = h = p;
}
else
{
if(p->data == t->data)
{
free(p);
}
else
{
t = t->next = p;
}
}
}
if(h1->next)
{
s = h1->next;
}
else
{
s = h2->next;
}
while(s)
{
p = s;
s = s->next;
p->next = NULL;
if(p->data == t->data)
{
free(p);
}
else
{
t = t->next = p;
}
}
h1->next = h;
return h1;
}
版本2
#include <stdio.h>
#include <stdlib.h>
#define N 5
#define M 8
typedef struct node
{
int data;
struct node * next;
}ElemSN;
ElemSN * Createlink(int a[],int n);//创建带表头单向链表
void Printlink(ElemSN *h);//打印带表头单向链表
void fun(ElemSN *h1,ElemSN *h2);//升序
int main()
{
int a[N] = {2,2,4,4,6};
int b[M] = {1,2,2,3,3,4,4,5};
ElemSN *head1,*head2;
//创建带表头单向链表
head1 = Createlink(a,5);
head2 = Createlink(b,8);
//打印原链表
printf("原链表1为:");
Printlink(head1);
printf("\n");
printf("原链表2为:");
Printlink(head2);
printf("\n");
//升序
printf("升序结果为:");
fun(head1,head2);
free(head2);
Printlink(head1);
printf("\n");
return 0;
}
//创建带表头单向链表
ElemSN * Createlink(int a[],int n)
{
ElemSN *h,*t,*p;
h = (ElemSN *)malloc(sizeof(ElemSN));
t = h;
for(int i = 0;i < n;i++)
{
p = (ElemSN *)malloc(sizeof(ElemSN));
p->data = a[i];
p->next = NULL;
t->next = p;
t = p;
}
return h;
}
//打印链表
void Printlink(ElemSN *h)
{
ElemSN *p;
for(p = h;p->next;p = p->next)
{
printf("%d ",p->next->data);
}
}
//升序
void fun(ElemSN *h1,ElemSN *h2)
{
ElemSN *s,*p,*t,*h;
h = NULL;
while(h1->next && h2->next)
{
if(h1->next->data < h2->next->data)
{
p = h1->next;
h1->next = p->next;
}
else
{
p = h2->next;
h2->next = p->next;
}
p->next = NULL;
if(!h)
{
t = h = p;
}
else
{
if(p->data == t->data)
{
free(p);
}
else
{
t = t->next = p;
}
}
}
if(h1->next)
{
s = h1->next;
}
else
{
s = h2->next;
}
while(s)
{
p = s;
s = s->next;
p->next = NULL;
if(p->data == t->data)
{
free(p);
}
else
{
t = t->next = p;
}
}
h1->next = h;
}