单循环链表的逆序输出
#include<iostream>
#include<malloc.h>
using namespace std;
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
bool InitList(LinkList &L,int n)
{
L=(LinkList)malloc(sizeof(LNode));
if(L==NULL)
{
return false;
}
L->next = L;
int data;
for(int i=1;i<=n;i++)
{
cin>>data;
LNode *s =(LNode*)malloc(sizeof(LNode));
s->data = data;
s->next = L->next;
L->next = s;
}
return true;
}
bool reverse(LinkList &L)
{
LNode* p =(LNode*)malloc(sizeof(LNode));
LNode* m =(LNode*)malloc(sizeof(LNode));
m = L;
p = L->next;
int len = 0;
while(p!=L)
{
p = p->next;
len++;
}
p = L;
int i = 0;
int a2;
while(i<len-1)
{
while(p->next!=L)
{
p = p->next;
}
a2 = p->data;
LNode* s =(LNode*)malloc(sizeof(LNode));
s->data = a2;
s->next=m->next;
m->next = s;
i++;
m = m->next;
p = L->next;
while(p->next->next!=L)
{
p = p->next;
}
LNode* q =(LNode*)malloc(sizeof(LNode));
q = p->next;
p->next = q->next;
free(q);
p = L->next;
}
return true;
}
void Print(LinkList L)
{
LNode * p=(LNode *)malloc(sizeof(LNode));
p = L->next;
while(p!=L)
{
cout<<p->data<<" ";
p = p->next;
}
}
int main()
{
LinkList L;
bool res,r;
cout<<"请输入数据"<<endl;
res = InitList(L,5);
if( res==false)
{
cout<<"链表创建失败!"<<endl;
}
cout<<"链表为:"<<endl;
Print(L);
cout<<endl;
r = reverse(L);
if(r==false)
{
cout<<"失败!"<<endl;
}
else
{
cout<<"逆序结果为:"<<endl;
Print(L);
cout<<endl;
}
}