線性表演算法實現

炸天幫陳長生發表於2018-10-27

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;

}



相關文章