Created
December 15, 2019 21:59
-
-
Save kaili302/3ad2242674c86ee3c9d1924a88fd42b9 to your computer and use it in GitHub Desktop.
合并list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <malloc.h> | |
typedef int ElemType; | |
typedef struct LNode //定义单链表结构 | |
{ | |
ElemType data; | |
struct LNode *next; | |
}LinkNode; | |
void InitList(LinkNode *&L) //初始化单链表 | |
{ | |
L=(LinkNode *)malloc(sizeof(LinkNode)); | |
L->next=NULL; | |
} | |
void CreateList(LinkNode *&L,ElemType a[],int n) //创建单链表 | |
{ | |
LinkNode *s; | |
L=(LinkNode *)malloc(sizeof(LinkNode)); | |
L->next=NULL; | |
for(int i=0;i<n;i++) | |
{ | |
s=(LinkNode *)malloc(sizeof(LinkNode)); | |
s->data=a[i]; | |
s->next=L->next; | |
L->next=s; | |
} | |
} | |
void sort(int R[],int n) //对数组进行排序 | |
{ | |
int i,j,x; | |
for(i=0;i<n-1;i++) | |
for(j=n-1;j>i;j--) | |
{ | |
if(R[j]>R[j-1]) | |
{ | |
x=R[j]; | |
R[j]=R[j-1]; | |
R[j-1]=x; | |
} | |
} | |
} | |
void DispList(LinkNode * L) //输出单链表 | |
{ | |
LinkNode *p=L->next; | |
while(p!=NULL) | |
{ | |
printf("%d",p->data); | |
p=p->next; | |
} | |
printf("\n"); | |
} | |
void contact(LinkNode *p1,LinkNode *p2,LinkNode *&L) //合并h,k两个单链表,生成单链表L | |
{ | |
LinkNode *r; | |
p1 = p1->next; | |
p2 = p2->next; | |
L = (LinkNode *)malloc(sizeof(LinkNode)); | |
L->next = NULL; | |
r = L; | |
while (p1 && p2) | |
{ | |
if(p1->data < p2->data) | |
{ | |
r->next = p1; | |
r = r->next; | |
p1 = p1->next; | |
} | |
else | |
{ | |
r->next = p2; | |
r = r->next; | |
p2 = p2->next; | |
} | |
} | |
if(p1) | |
r->next = p1; | |
else | |
r->next = p2; | |
} | |
void elemomit(LinkNode *L) //删除单链表L中的重复结点 | |
{ | |
LinkNode *p = L->next; | |
if (!p) | |
{ | |
return; | |
} | |
L = p->next; | |
while (L) | |
{ | |
if (L->data == p->data) | |
{ | |
p->next = L->next; | |
} | |
else | |
{ | |
p = L; | |
} | |
L = L->next; | |
} | |
} | |
int main() | |
{ | |
int a[10]={1,4,2,5,6,3,7,2,9,2}; | |
int b[10]={3,5,2,7,8,3,2,4,9,3}; | |
int c[20]; | |
LinkNode *h; | |
LinkNode *k; | |
LinkNode *m; | |
LinkNode *L; | |
printf("进行排序:\n"); | |
sort(a,10); | |
sort(b,10); | |
printf("初始化单链表h,k\n"); | |
InitList(h); | |
InitList(k); | |
printf("创建两个结点值分别为数组a,b元素的单链表h,k\n"); | |
CreateList(h,a,10); | |
CreateList(k,b,10); | |
printf("输出单链表h的元素:"); | |
DispList(h); | |
printf("输出单链表k的元素:"); | |
DispList(k); | |
printf("合并两个单链表h,k\n"); | |
contact(h,k,L); | |
printf("合并后单链表结点值为:"); | |
DispList(L); | |
printf("删除元素"); | |
elemomit(L); | |
printf("删除后元素为:"); | |
DispList(L); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment