通过一个数组建立链表,并将其反转。
#include<iostream>
using namespace std;
typedef struct list* pl;
typedef struct list l;
struct list
{
int data;
pl next;
};
pl L=new(l);
void makelist(pl L,int a[],int n)//建立链表
{
pl p=L;
for(int i=0;i<n;i++)
{
pl s=new(l);
s->data=a[i];
p->next=s;
p=p->next;
}
p->next=NULL;
}
void reverse(pl L)//链表反转
{
pl p=L->next,q;
L->next=NULL;
while(p)
{
q=p->next;
p->next=L->next;
L->next=p;
p=q;
}
}
void printlist(pl L)//打印链表
{
pl p=L->next;
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int main()
{
int a[5]={1,2,3,4,5};
makelist(L,a,5);
printlist(L);
reverse(L);
printlist(L);
return 0;
}
本文介绍了一个使用C++实现的过程,该过程将数组转换为链表,并实现了链表的反转。通过具体的代码示例,展示了如何构建链表、如何反转链表以及如何打印链表的内容。
1015

被折叠的 条评论
为什么被折叠?



