双向链表的奇偶节点交换(即1节点和2节点交换,然后3节点和4节点交换)

来源:互联网 发布:mac outlook windows 编辑:程序博客网 时间:2024/05/21 19:23

双向链表的奇偶节点交换(即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;      //Node* head;      //Node* tail;      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)      {          //p=p->next;          if(p->next)          {              Node* temp;              temp=p->next;              //将最后节点衔接到P              p->next=temp->next;              if(temp->next!=NULL)              temp->next->pre=p;              //将前节点先接到temp              temp->pre=p->pre;              if(p->pre!=NULL)              p->pre->next=temp;              temp->next=p;              //temp=p->pre;              p->pre=temp;              //p=temp;              p=p->next;          }      }  }  
原创粉丝点击