用C语言代码实现:有一个整数单链表A,设计一个算法,将其拆分成两个单链表A和B,使得A单链表中含有所有的偶数结点,B单链表含有所有的奇数结点,且保持原来的相对次序
时间: 2024-05-21 08:11:13 浏览: 18
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}Node;
Node *createList(int n); //创建链表
void splitList(Node *A, Node **B); //拆分链表
void printList(Node *head); //打印链表
int main()
{
int n;
Node *A, *B=NULL;
printf("请输入链表的长度:");
scanf("%d",&n);
A = createList(n);
printf("原链表为:");
printList(A);
splitList(A, &B);
printf("偶数链表为:");
printList(A);
printf("奇数链表为:");
printList(B);
return 0;
}
Node *createList(int n)
{
Node *head=NULL, *p=NULL, *tail=NULL;
int i, data;
for(i=0; i<n; i++){
printf("请输入第%d个节点的值:",i+1);
scanf("%d",&data);
p = (Node*)malloc(sizeof(Node));
p->data = data;
p->next = NULL;
if(head==NULL){
head = p;
tail = p;
}else{
tail->next = p;
tail = p;
}
}
return head;
}
void splitList(Node *A, Node **B)
{
Node *p, *q;
while(A!=NULL && A->data%2==0){ //找到第一个奇数结点
A = A->next;
}
if(A==NULL) return;
*B = A; //将第一个奇数结点作为新链表B的头结点
p = A->next;
q = A;
while(p!=NULL){
if(p->data%2==0){ //偶数结点
q->next = p->next; //将p从A中删除
p->next = NULL;
q = p;
p = q->next;
}else{ //奇数结点
q = p;
p = p->next;
}
}
}
void printList(Node *head)
{
Node *p;
for(p=head; p!=NULL; p=p->next){
printf("%d ",p->data);
}
printf("\n");
}
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)