实现一单链表的逆置,并输出逆置前后的结果。。。
写的简单一点,参考写法:
#include<iostream>
using namespace std;
typedef struct list
{
int data;
struct list *next;
;}LIST;
LIST * creat()//创建链表
{
LIST *head,*p;
int flag=1,d;
head = new LIST;
p = head;
cout<<"输入数据\n";
cin>>d;
head ->data = d;
while(flag)
{
LIST *tem = new LIST;
cout<<"输入数据\n";
cin>>d;
if(0!=d)//输入0结束
{
tem->data = d;
p->next = tem;
p = tem;
}
else flag = 0;
}
p->next = NULL;
return head;
}
LIST *reverse(LIST *head)//链表逆置
{
if(head == NULL ||head->next ==NULL)
return head;
LIST *p1,*p2,*p3;
p1 = head;
p2 = head->next;
while(p2)
{
p3 = p2->next;
p2->next = p1;
p1 = p2;
p2 = p3;
}
head->next = NULL;
head = p1;
return head;
}
void Delete(LIST *h)//销毁链表
{
while(h!=NULL)
{
LIST *p = h;
h=h->next;
delete p;
}
}
void show(LIST *head)//打印链表
{
if(head == NULL)
cout<<"链表为空\n";
while(head != NULL)
{
cout<<head->data<<" ";
head = head->next;
}
cout<<endl;
}
int main()
{
LIST *head;
head = creat();
cout<<"链表元素为:\n";
show(head);
cout<<"链表逆置后的为:\n";
head = reverse(head);
show(head);
Delete(head);
return 0;
}
本文详细介绍了如何实现单链表的逆置操作,并通过示例代码展示了逆置前后的链表变化。
2509

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



