1. 程式人生 > >兩條帶頭結點的升序重復合並成一個無重復的升序鏈表

兩條帶頭結點的升序重復合並成一個無重復的升序鏈表

++ while 復合 ace 升序 eof pri 帶頭結點 建立

#include<stdio.h>

#include<stdlib.h>

typedef struct node{

int data;

struct node * next;

}ElemSN;

ElemSN * Createlink(int a[],int n){ //建立帶表頭結點的鏈表

int i;

ElemSN * h, * p;

h=p=(ElemSN *)malloc(sizeof(ElemSN));

h->next=NULL;

for( i=0;i<n;i++){

p=p->next=(ElemSN *)malloc(sizeof(ElemSN));

p->data =a[i];

p->next=NULL;

}

return h;

}

void Fun(ElemSN*head1,ElemSN*head2){

ElemSN*h=NULL,*p,*t,*s;

while(head1->next&&head2->next) { //任意一條鏈表為空,循環結束。判斷剩余鏈表的頭結點與生成新鏈表的尾結點的值是否相同,

//相同則free(p),頭結點後移

if(head1->next->data<head2->next->data){

p=head1->next;

head1->next=p->next;

}

else{

p=head2->next;

head2->next=p->next;

}

p->next=NULL;

if(!h)

h=t=p;

else{

if(t->data==p->data)

free(p);

else

t=t->next=p;

}

}

if(head1->next)

s=head1->next;

else

s=head2->next;

while(s){

p=s;

s=s->next;

p->next=NULL;

if(p->data==t->data)

free(p);

else

t=t->next=p;

}

head1->next=h;

}

void Printlink(ElemSN * h){

ElemSN * p;

for(p=h;p->next;p=p->next)

printf("%2d\n",p->next->data);

}

int main(void){

int a[9]={1,2,4,4,5,7,7,8,9};

int b[8]={2,3,3,4,10,12,12,13};

ElemSN * head1,*head2;

head1=Createlink(a,9);

head2=Createlink(b,8);

Fun(head1,head2);

free(head2);

Printlink(head1);

}



兩條帶頭結點的升序重復合並成一個無重復的升序鏈表