C++编程实现单链表的逆置

实现一单链表的逆置,并输出逆置前后的结果。。。

写的简单一点,参考写法:
#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;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值