資料結構之倆迴圈單鏈表合併
阿新 • • 發佈:2019-01-04
這段時間要好好調整一下自己了,發現基礎才是王道,所以打算好好鋪一鋪我滴c指標這一塊了,所以資料結構將會斷更一段時間,不過接下來要和大家見面的就是我們上次的迴圈單鏈表之合併
題目:將連結串列a和連結串列b合併為連結串列c
演算法思想
將a連結串列的尾指標reara與b連結串列的第一個節點連結起來,並且修改b連結串列的尾指標rearb,使得它指向連結串列a的頭結點
程式碼
#include<stdio.h>
#include<malloc.h>
typedef struct node
{
int data;
struct node*next ;
}node,*list;
list L_list()
{
list llist;
int num;
node*p;
llist=(node*)malloc(sizeof(struct node));
llist->data=-1;
llist->next=llist;
puts("input value -1 over");
scanf("%d",&num);
while(num!=-1)
{
p=(node*)malloc(sizeof(struct node));
p->data=num;
p->next =llist->next;
llist->next=p;
scanf("%d",&num);
}
p=llist;
while(p->next!=llist)
{
p=p->next;
}
return p;
}
list merge(list reara,list rearb)
{
node *p;
p=reara->next;
reara->next=rearb->next->next;
free(rearb->next );
rearb->next=p;
return rearb;
}
void print(list cl)
{
node*p;
p=cl->next->next;
while(p!=cl->next)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
int main()
{
list clista,clistb,clistc;
printf("input clista:\n");
clista=L_list();
puts("the clista:");
print(clista);
printf("input clistb:\n");
clistb=L_list();
puts("the clistb:");
print(clistb);
clistc=merge(clista,clistb);
puts("the merge:\n");
print(clistc);
return 0;
}
總結
這一次的程式碼主要精髓在於如何處理兩個連結串列合併後的關係,所以這一次的難題就是這裡了