链表相邻元素翻转,如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);
}