链表相邻元素翻转

链表相邻元素翻转,如a->b->c->d->e->f-g,翻转后变为:b->a->d->c->f->e->g 

解:三个指针,p和q两个节点作为一组处理,pre用于链接不同组的节点。

#include <iostream>
#include <stdio.h>
using namespace std;

typedef struct LNode{
	int data;
	struct LNode* next;
}LNode,*List;

void InsertList(List &L, int data)
{
	LNode* p=L;
	if(L==NULL)
	{
		L=new LNode;
		L->data=data;
		L->next=NULL;
	}
	else
	{
		while(p->next )
			p=p->next;
		LNode *q=new LNode;
		p->next=q;
		q->data=data;
		q->next=NULL;	
	}
}

void TraverseList(List L)
{
	LNode *p=L;
	while(p)
	{
		cout<<p->data<<"  ";
		p=p->next;
	}
	cout<<endl;
}

void reverse(List &L)
{
	LNode *p=L;
	LNode *q=p->next;
	LNode* pre=NULL;
	if(!p || !q)  return ;
	while(p && q)
	{
		if(L==p) L=q;
		if(pre)
			pre->next=q;

		pre=p;
		p->next=q->next;
		q->next=p;
		p=p->next;
		if(!p) return ;
		q=p->next;
	}
		
}

void main()
{
	List L=NULL;
	InsertList(L,10);
	InsertList(L,9);
	InsertList(L,8);
	InsertList(L,7);
	InsertList(L,6);
	InsertList(L,5);
	InsertList(L,4);
	InsertList(L,3);
	
	cout<<"翻转前:";
	TraverseList(L);
	
	reverse(L);
	cout<<"翻转后:";
	TraverseList(L);
	
	
	
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值