首页 > 代码库 > 奇数在前偶数在后。各自反转后相连
奇数在前偶数在后。各自反转后相连
#include <iostream>#include <stdlib.h>using namespace std;struct node { struct node *next; int value;};node *CreateListNode(int value){ if(value=http://www.mamicode.com/=NULL) return NULL; node *pNode=(node*)malloc(sizeof(node)); pNode->value=http://www.mamicode.com/value; pNode->next=NULL; return pNode;}void ConnectNodes(node*pCurrent,node* pNext){ if (pCurrent==NULL) { cout<<"Error to connect two nodes."<<endl; exit(1); } pCurrent->next=pNext;}void PrintList(node* pHead){ node *pNode=pHead; while (pNode!=NULL) { cout<<pNode->value<<" "; pNode=pNode->next; } cout<<endl;}struct node *reverse(struct node *list){ if (list==NULL) return NULL; if(list->next==NULL) return list; node* tPre=list; node* tmp=list->next; while (tmp) { node* tNext=tmp->next; tmp->next=tPre; tPre=tmp; tmp=tNext; } list->next=NULL; list=tPre; return list;}struct node *swap(struct node *list){ if (list==NULL) return NULL; if (list->next==NULL) return list; node *p=list; node *OddHead=(node*)malloc(sizeof(node)); node *EvenHead=(node*)malloc(sizeof(node)); node *Odd=OddHead; node *Even=EvenHead; while (p) { if (p->value%2==0) { Even->next=p; Even=p; } else { Odd->next=p; Odd=p; } p=p->next; } Even->next=NULL; Odd->next=NULL; Even=reverse(EvenHead->next); Odd=reverse(OddHead->next); OddHead=Odd; while (Odd->next) Odd=Odd->next; Odd->next=Even; return OddHead; //return OddHead;}int main(){ node *pNode1=CreateListNode(4); node *pNode2=CreateListNode(5); node *pNode3=CreateListNode(7); node *pNode4=CreateListNode(1); node *pNode5=CreateListNode(6); ConnectNodes(pNode1,pNode2); ConnectNodes(pNode2,pNode3); ConnectNodes(pNode3,pNode4); ConnectNodes(pNode4,pNode5); node* p=swap(pNode1); PrintList(p); return 0;}
奇数在前偶数在后。各自反转后相连
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。