【数据结构】单链表—单链表拆分
将一个带有头结点的单链表A分为两个带头结点的单链表A和B,使得A表中含有原表中序号为奇数的元素,而表B中含有原表中序号为偶数的元素,且保持相对顺序不变。#include<stdio.h>#include<stdlib.h>struct Lnode{int data;Lnode *next;};int Init(struct Lnode...
·
将一个带有头结点的单链表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;
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)