您的位置:首页 > 其它

将一个链表中结点的值按奇偶拆分,使其中一个链表结点的值为偶数,另一个为奇数

2016-10-29 10:51 357 查看
这是一道笔试题,其实也挺简单,但是在当时笔试的时候,却怎么也想不出做不出来,最后还是写错了。事后在机器上又写了一下,这算是一个总结吧。

综其原因,还是自己平时程序写的少,想的少,从而导致在关键时候由于紧张想不出写不出。

平时就多练习吧。菜鸟多努力!

这个程序实现的功能就是:将一个链表中结点的值按奇偶拆分,使其中一个链表结点的值为偶数,另一个为奇数

具体程序如下:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef struct node
{
int value;
struct node *next;
}Node,*pNode;

pNode CreateList(int n)
{
pNode head,p,new;
int i;
printf("链表节点的值:");
head=(pNode)malloc(sizeof(Node));
scanf("%d",&(head->value));
head->next=NULL;
p=head;

for (i=0;i<n-1;i++)
{
new=(pNode)malloc(sizeof(Node));
scanf("%d",&(new->value));
p->next=new;
p=new;
}
p->next=NULL;
return head;
}

void display(pNode head)
{
while (head!=NULL)
{
printf("%d ",head->value);
head=head->next;
}
printf("\n");
}

void DivideList(pNode head,Node **odd,Node **even)
{
pNode p,q,r;

assert(head!=NULL);

while (head!=NULL)
{

p=head;
if (p->value%2==0)
{
if (*even==NULL)
{
*even=p;
q=*even;
}
head=head->next;
q->next=p;
q=p;
q->next=NULL;
}
else
{
if (*odd==NULL)
{
*odd=p;
r=*odd;
}
head=head->next;
r->next=p;
r=p;
r->next=NULL;
}
}
}

void DestoryList(pNode head)
{
pNode p;
while(head!=NULL)
{
p=head;
head=head->next;
free(p);
}
free(head);
}

int main()
{
int n;
pNode head;
pNode odd=NULL,even=NULL;
printf("链表长度:");
scanf("%d",&n);
head=CreateList(n);
//	display(head);

DivideList(head,&odd,&even);
display(odd);
display(even);

DestoryList(odd);
DestoryList(even);

system("pause");
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐