/*
* 将链表的奇偶位交换,不能使用交换链表中的值这种做法。
* 题意即将链表: 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~