双向链表的奇偶节点交换(即1节点和2节点交换,然后3节点和4节点交换)
#include<iostream>
#include<string>
#include<vector>
#include<iterator>
using namespace std;
typedef struct Node
{
struct Node* next;
struct Node* pre;
int data;
}Node;
typedef struct D_List
{
Node* head;
Node* tail;
int size;
}D_List;
bool creat_DList(D_List &l,int val)
{
Node* node=(Node*)malloc(sizeof(Node));
node->next=NULL;
node->pre=NULL;
node->data=val;
l.head=node;
l.tail=node;
if(node!=NULL)
return true;
else
return false;
}
bool insert_DList(D_List &l,int val)
{
Node* node=(Node*)malloc(sizeof(Node));
node->data=val;
node->next=NULL;
l.tail->next=node;
node->pre=l.tail;
l.tail=node;
if(node!=NULL)
return true;
else
return false;
}
void func(D_List& l);
int main()
{
D_List l;
creat_DList(l,1);
insert_DList(l,2);
insert_DList(l,3);
insert_DList(l,4);
insert_DList(l,5);
insert_DList(l,6);
insert_DList(l,7);
insert_DList(l,8);
insert_DList(l,9);
insert_DList(l,10);
insert_DList(l,11);
insert_DList(l,12);
insert_DList(l,13);
cout<<l.head->data<<l.head->next->data<<endl;
cout<<l.tail->data<<l.tail->pre->data<<endl;
func(l);
Node *p=l.head;
while(p)
{
cout<<p->data<<endl;
p=p->next;
}
return 0;
}
void func(D_List& l)
{
Node* p=l.head;
l.head=p->next;
while(p&&p->next)
{
if(p->next)
{
Node* temp;
temp=p->next;
p->next=temp->next;
if(temp->next!=NULL)
temp->next->pre=p;
temp->pre=p->pre;
if(p->pre!=NULL)
p->pre->next=temp;
temp->next=p;
p->pre=temp;
p=p->next;
}
}
}