成对交换双向链表中的结点

头文件:

#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);
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值