头文件:
#include <iostream>
class ListNode
{
public:
ListNode* next;
ListNode* pre;
int val;
ListNode(int x):val(x),next(NULL),pre(NULL){};
};
源文件:
#include "ListNode.h"
#include <vector>
#include <iostream>
using namespace std;
void ConnectNode(vector < ListNode* > &data,int n)
{
int i=0;
ListNode* preNode1=NULL;
while(i<n-1)
{
data[i]->next = data[i+1];
data[i]->pre=preNode1;
preNode1=data[i];
++i;
}
data[i]->pre=preNode1;
data[i]->next=NULL;
}
void PrintVal(ListNode* head)
{
while (head != NULL)
{
cout<<head->val<<" ";
head=head->next;
}
cout<<endl;
}
ListNode* preNode=NULL;
ListNode* swapPairs(ListNode* head)
{
if(head == NULL || head->next == NULL)
return head;
ListNode* newHead = head->next;
head->next = swapPairs(newHead->next);
newHead->next = head;
head->pre = newHead;
newHead->pre = preNode;
preNode=head;
return newHead;
}
void main()
{
ListNode* node1=new ListNode(1);
ListNode* node2=new ListNode(2);
ListNode* node3=new ListNode(3);
ListNode* node4=new ListNode(4);
ListNode* node5=new ListNode(5);
vector<ListNode* > NodeVector;
NodeVector.push_back(node1);
NodeVector.push_back(node2);
NodeVector.push_back(node3);
NodeVector.push_back(node4);
NodeVector.push_back(node5);
ConnectNode(NodeVector,5);
PrintVal(node1);
cout<<"<<<<<"<<" After swap "<<"<<<<<<<<<<"<<endl;
ListNode* head=swapPairs(node1);
PrintVal(head);
}