1.设有两个无头结点的单链表,头指针分别为ha.hb.链中有数据域data链域next,两链表的数据都按递增序存放,现要求将hb表归到ha表中且归并后ha仍递增序,归并中ha表中已有的数据若hb中也有则hb中的数据不归并到ha中要求不申请额外的存储空间来完成。merge(hahb);
linklist.h
//
// Linklist.h
// Test
//
// Created by Edong on 2018/10/27.
// Copyright © 2018 Edong. All rights reserved.
//
#ifndef Linklist_h
#define Linklist_h
#include <stdlib.h>
#include <stdio.h>
#endif /* Linklist_h */
typedef int elemtype;
typedef struct node{
elemtype data;
struct node* next;
}*linklist;
// 传入一个数组,用于初始化链表
linklist initlist(int arg[]){
int lenth=0;
for (; arg[lenth]!='\0'; lenth++);
if (lenth==0) return NULL;
linklist list=(linklist)malloc(sizeof(linklist));
list->data=arg[0];
list->next=NULL;
for (int i=lenth; i>1; i--) {
linklist p=(linklist)malloc(sizeof(linklist));
p->data=arg[i-1];
p->next=list->next;
list->next=p;
}
return list;
}
void printList(linklist L){
linklist p=L;
while(p!=NULL){
printf("%d,",p->data);
p=p->next;
}
}
//合并排序
void sortList(linklist a,linklist b){
int flag=0;
linklist copyB=b;
linklist copyA=a;
linklist copyA2=a;
while(copyB){
if(copyA->next==NULL&&(copyB->data)>(copyA->data)){
copyA->next=copyB;
break;
}
if (copyB->data==copyA->data) {
copyB=copyB->next;
continue;
}
if (copyB->data<copyA->data) {
if (flag==0) copyA=copyA->next;
copyA2->next=copyB;
copyB=copyB->next;
copyA2->next->next=copyA;
if (flag==0){
elemtype data=copyA2->data;
copyA2->data=copyA2->next->data;
copyA2->next->data=data;
flag=2;
copyA=copyA2->next;
continue;
}
copyA2=copyA2->next;
continue;
}
if(copyB->data>copyA->data){
copyA=copyA->next;
if (flag!=0)copyA2=copyA2->next;
else flag=1;
}
}
}
main.c
#include <stdio.h>
#include "Linklist.h"
#define MAXSIZE 30
int main(int argc, const char * argv[]) {
int a[MAXSIZE]={1,3,5,7};
int b[MAXSIZE]={2,4,6,8,10} ;
linklist al=initlist(a);
linklist bl=initlist(b);
printf("\n链表a为:");
printList(al);
printf("\n链表b为:");
printList(bl);
printf("\n链表b、a合并后:");
sortList(al, bl);
printList(al);
printf("\n");
return 0;
}