交换链表的奇偶节点

给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。

请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性,如下实例。

示例 :

输入: 1->2->3->4->5->NULL

输出: 1->3->5->2->4->NULL

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct student{
	char name[20];
	float score;
	int node;
	struct student *next;
}*head,*p1,*p2;

//输出链表
void PrintLink(struct student *head){
	struct student *p;
	int n=0;
	p=head->next;
	while(p!=NULL){
		printf("第%d个节点:节点:%d\t 姓名:%s\t 成绩:%.2f\t\n",++n,p->node,p->name,p->score);
		p=p->next;
	}
}

//交换奇偶节点,同时对奇偶节点进行重排列;
//循环结束后,将最后指向的偶节点的next置为NULL,
//再将最后指向的奇节点的next指向一开始存到p中的第二个节点,完成奇偶交换。
void Exchange(struct student *head){
	struct student *p1,*p2,*p;    //p1为第一个节点,p和p2为第二个节点
	p1=head->next;
	p=p2=p1->next;
	
	while(p1->next!=NULL&&p1->next->next!=NULL){
		p1->next=p1->next->next;
		p1=p1->next;

		if(p2->next!=NULL&&p2->next->next!=NULL){
			p2->next=p2->next->next;
			p2=p2->next;
		}
	}
	p2->next=NULL;
	p1->next=p;

}
void main(){
	int n=0;
	//建立一个带头节点的链表
	head=(struct student *)malloc(sizeof(struct student));
	do{
		p1=(struct student *)malloc(sizeof(struct student));
		if(++n==1){
			head->next=p1;
		}else
			p2->next=p1;
		printf("Please input the %dth student's name:",n);
		gets(p1->name);
		if(strcmp(p1->name,"0")==0){
			p2->next=NULL;
			free(p1);
			break;
		}
		printf("Please input the %dth student's score:",n);
		scanf("%f",&p1->score);getchar();
		p1->node=n;
		p1->next=NULL;
		p2=p1;
	}while(1);
	printf("=================================RESULT=================================\n");
	PrintLink(head);
	Exchange(head);

	printf("\n交换后\n");
	PrintLink(head);
	
}

 

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值