【2013微软校招面试题】将链表的奇偶位交换,不能使用交换链表中的值这种做法。

9 篇文章 0 订阅
1 篇文章 0 订阅

 /*
 *  将链表的奇偶位交换,不能使用交换链表中的值这种做法。
 *  题意即将链表:  head->1->2->3->4->……     变成 head->2->1->4->3->……
 *
 */

 

解题思路:直接遍历链表进行处理即可,注意指针的赋值等细节即可~详见代码如下:

 

#include <iostream>
using namespace std;

const int MAX = 9;

struct node{
	int value;
	node *next;
};

node * SwitchEvenAndOdd(node * head)
{
	if(head == NULL || head->next == NULL)  //0个 or 1个节点 
		return head;
	
	node temp;   //定义一个哑节点
	temp.next = head;

	node * cur = &temp,*p;  //定义了两个辅助指针
	while(cur->next != NULL && ((p = cur->next->next) != NULL) )  //剩下不止一个节点
	{
		cur->next->next = p->next;
		p->next = cur->next;
		cur->next = p;
		cur = cur->next->next;
	}
	return temp.next;
}

node * ConnectList(node *arr)  //用数组生成链表
{
	for(int i=0; i<MAX-1; i++)
		arr[i].next = &arr[i+1];
	arr[MAX-1].next = NULL;
	return &arr[0];
}

void print(node * head) //打印输出链表
{
	while(head)
	{
		cout<<head->value<<"\t";
		head = head->next;
	}
	cout<<endl;
}

int main()
{
	node arr[MAX];
	for(int i=0; i<MAX; i++)
	{
		arr[i].value = i+1;
		arr[i].next = NULL;
	}
	//begin to work
	node *head = ConnectList( arr );
	head = SwitchEvenAndOdd(head);
	print( head );
	return 0;
}


欢迎读者留言探讨~O(∩_∩)O~

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值