您的位置:首页 > 其它

将链表中的所有元素为奇数的节点移到元素为偶数节点的前面,并使奇数之间顺序反转,偶数之间顺序反转。

2016-09-08 10:50 330 查看
将链表中的所有元素为奇数的节点移到元素为偶数节点的前面,并使奇数之间顺序反转,偶数之间顺序反转。

示例:
交换前链表的顺序           交换后链表的顺序
4→5→7→1→6   ==>  1→7→5→6→4
1                ==>  1                   (链表仅含一个元素)
2→1            ==>  1→2 
                   ==>                        (链表为空)
 
C/C++:
链表节点定义为:
struct node {
struct node *next;
int value;
};
struct node*swap(struct node *list);
#include<iostream>

using namespace std;

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

node * CreateListNode(int value)//链表中创建节点
{
if(value == NULL)
return NULL;
node *pNode = new node();
pNode->value = value;
pNode->next =NULL;
return pNode;
}

void ConnectListNodes(node *pCurrent, node *pNext)	// 连接两个节点
{
if(pCurrent == NULL)
{
cout<<"Error to connect two nodes."<<endl;
exit(1);
}
pCurrent->next = pNext;
}

void PrintList(node *pHead)
{
cout<<"PrintList start."<<endl;
node *pNode = pHead;
while(pNode != NULL)
{
cout<<pNode->value;
pNode = pNode->next;
}
cout<<endl;
cout<<"PrintList"<<endl;
}

void Destroy(node *pHead)
{
node *pNode = pHead;
while(pNode != NULL)
{
pHead = pHead->next;
delete pNode;
pNode = pHead;
}
}

//返回,p所对应位置的下一个位置对应的值
int dqExchage(struct node *list1,struct node *list2,struct node *list3,int p)
{
if(p %2 ==0){//偶数
while(list1->next && list1->value % 2 !=0){
list1=list1->next;
}
list2=list1;
}

int tmp=list1->value;
int q = p;
while( list1->next && list1->value !=q){
list1->value = p;
p = tmp;
list1 = list1->next;
tmp = list1->value;

}
list1->value = p;

if(list1->next){
return list1->next->value;
}else{
return NULL;
}

}
//思路分析
// 特殊的插入排序
//针对奇数,插入到最前面,针对偶数,插入到前面奇数的后面,使其成为第一个偶数
struct node *swap(struct node *list)
{
node *pHead = list;
node *pHead1 = list;

//0
if(list->next){
int p=list->next->value;
while(p != NULL){
p=dqExchage(list, list, list,p);

}
return list;
}else{
return NULL;
}

}

void Test1()
{
node *pNode1 = CreateListNode(4);
node *pNode2 = CreateListNode(5);
node *pNode3 = CreateListNode(7);
node *pNode4 = CreateListNode(1);
node *pNode5 = CreateListNode(6);

ConnectListNodes(pNode1, pNode2);
ConnectListNodes(pNode2, pNode3);
ConnectListNodes(pNode3, pNode4);
ConnectListNodes(pNode4, pNode5);
PrintList(pNode1);
PrintList(swap(pNode1));
}

void Test2()
{
node *pNode1 = CreateListNode(4);
node *pNode2 = CreateListNode(2);
node *pNode3 = CreateListNode(7);
node *pNode4 = CreateListNode(8);
node *pNode5 = CreateListNode(6);

ConnectListNodes(pNode1, pNode2);
ConnectListNodes(pNode2, pNode3);
ConnectListNodes(pNode3, pNode4);
ConnectListNodes(pNode4, pNode5);
PrintList(pNode1);

PrintList(swap(pNode1));
}

int main()
{
cout<<"Test1"<<endl;

Test1();
cout<<"Test2"<<endl;
Test2();
//
system("pause");
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐