.将链表中的所有元素为奇数的节点移到元素为偶数节点的前面,并保证奇数之间顺序不变,偶数之间顺序不变。
示例:
交换前链表的顺序 交换后链表的顺序
4→5→3→1→2 ==> 5→3→1→4→2
1 ==> 1 (链表仅含一个元素)
2→1 ==>1→2
==> (链表为空)
C/C++:
链表节点定义为:
struct node {
struct node *next;
int value;
};
struct node *swap(struct node*list);
Java:
链表节点定义为:
classNode {
publicNode next;
public int value
}
Nodeswap(Node list)
注意点和要求如下:
1. swap函数要求对节点的指针/引用进行操作(不得创建任何新的链表节点)
2. 不得使用任何库函数/API,如需使用类似功能, 请自行实现
3.不得将链表转化为其他类型数据结构再进行交换,如数组等
#include <iostream>
#define Max 5
using namespace std;
struct node {
struct node *next;
int value;
};
void CreatelistF(node *&L, int a[], int n)
{
L = (node *)malloc(sizeof(node));
L->value = n;
L->next = NULL;
for (int i = 0; i < n; i++)
{
node *s = (node *)malloc(sizeof(node));
s->value = a[i];
s->next = L->next;
L->next = s;
}
}
void Print(node *&L)
{
node *temp;
temp = L->next;
while (temp != NULL)
{
printf("%d->", temp->value);
temp = temp->next;
}
cout << endl;
}
void Reverse(node *&L)
{
node *p = L->next, *q;
L->next = NULL;
while (p != NULL)
{
q = p->next;
p->next = L->next;
L->next = p;
p = q;
}
}
struct node *swap(struct node *list)
{
if (list == NULL)
return NULL;
if (list->next == NULL)
return list;
node *p = list->next;
node *OddHead = (node *)malloc(sizeof(node));
node *EvenHead = (node *)malloc(sizeof(node));
node *Odd = OddHead;
node *Even = EvenHead;
while (p)
{
if (p->value % 2 == 1)
{
Even->next = p;
Even = p;
}
else
{
Odd->next = p;
Odd = p;
}
p = p->next;
}
Odd->next = NULL;
Even->next = OddHead->next;
return EvenHead;
}
int main()
{
int a[Max] = {4,5,3,1,2};
node * L = (node *)malloc(sizeof(node));
CreatelistF(L, a, Max);
Reverse(L);
cout << "the old list" << endl;
Print(L);
L = swap(L);
cout << "the new list" << endl;
Print(L);
system("pause");
return 0;
}