將一個帶有頭結點的單鏈表A分爲兩個帶頭結點的單鏈表A和B,使得A表中含有原表中序號爲奇數的元素,而表B中含有原表中序號爲偶數的元素,且保持相對順序不變。
#include<stdio.h>
#include<stdlib.h>
struct Lnode
{
int data;
Lnode *next;
};
int Init(struct Lnode *L, int i)
{
struct Lnode *p;
struct Lnode *q=L;
int j=0;
while(j<i)
{
p = (struct Lnode *)malloc(sizeof(struct Lnode));
scanf("%d",&(p->data));
p->next =NULL;
q->next = p;
q= p;
j++;
}
return 0;
}
dis_creat(struct Lnode *A,struct Lnode *B)
{
int i = 1;
struct Lnode *q,*p,*t,*pre;
pre = A;
q = A->next;
t= B;
while(q!=NULL)
{
if(i%2==1)
{
pre = q;
q= q->next;
i++;
}
else if(i%2==0)
{
p = (struct Lnode *)malloc(sizeof(struct Lnode));
p->data = q->data;
p->next =NULL;
t->next = p;
t = p;
pre->next = q->next;
free(q);
q = pre->next;
i++;
}
}
return 0;
}
int main()
{
struct Lnode A,B;
struct Lnode *p=&A;
struct Lnode *q;
p->next = NULL;
int i = 10;
Init(p,i);
dis_creat(p,&B);
p = p->next;
q = B.next;
printf("這是A鏈表的元素:\n");
while(p!=NULL)
{
printf("%d\t",p->data);
p = p->next;
}
printf("\n這是B鏈表的元素:\n");
while(q!=NULL)
{
printf("%d\t",q->data);
q =q->next;
}
return 0;
}