双向链表的奇偶节点交换(即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;
		}
	}
	
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值