交换单链表中相邻的两个点(人搜)

/*************************************************************
 * file:reverse_twins_node_of_list.c
 * brief:交换单链表中相邻的两个点
 * yejing@2015.1.20    1.0      creat
 *************************************************************/
#include <stdio.h>
#include <stdlib.h>

typedef struct _node_t{
	struct _node_t *next;
	int value;
}node_t;

node_t* creat_list(int n){
	if(!n)
	 return NULL;
	int i = 1;
	node_t* phead = (node_t*)malloc(sizeof(node_t));
	phead->next  = NULL;
	phead->value = 1;
	if(!phead)
		return NULL;
	node_t *p, *q;
	p = q = phead;
	
	for(i = 1; i < n; ++i){
		q = (node_t*)malloc(sizeof(node_t));
		p->next = q;
		p = q;
		p->value = i + 1;
	}
	return phead;
}

node_t* reverse_twins_node_of_list(node_t* phead){
	if(!phead)
		return NULL;
	if(!phead->next)
		return phead;
	int i = 2;
	node_t* n = phead;
	phead = phead->next->next;
	while(i){
		node_t* m = n;
		n = n->next;
		m->next = phead;
		phead = m;
		--i;
	}
	phead->next->next = reverse_twins_node_of_list(phead->next->next);
	return phead;
}

void show_list(node_t* phead, int before_after){
	if(!phead)
		return;
		
	node_t* tmp = phead;
	if(before_after)
		printf("before transfer ");
	else
		printf("after  transfer ");
	printf("list is:");	
	while(tmp){
		printf(" %d", tmp->value);
		tmp = tmp->next;
	}
	printf("\n");
	return;
}

int main(int argc, char* argv[]){
	int count;
	printf("input list node count:\n");
	scanf("%d", &count);
	getchar();
	node_t* phead = creat_list(count);
	show_list(phead, 1);
	phead = reverse_twins_node_of_list(phead);
	show_list(phead, 0);
	
	return 1;
}
执行结果:





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值