链表的创建、逆序等操作

#include "iostream.h"
typedef  struct  List
{
 int a;
    List *pListNext;
}LIST;
void BuildList(LIST * &head,int n);//建立新的链表
void RevertList(LIST * &head);//链表逆序
void main()
{
 LIST *head=new LIST;
 LIST *head1=new LIST;
 BuildList(head,3);
  while(head)
  {
   cout<<head->a<<endl;
   head=head->pListNext;
  }
  cout<<"下面是逆序的结果:"<<endl;
 
  BuildList(head1,3);

  RevertList(head1);
    while(head1)
  {
   cout<<head1->a<<endl;
   head1=head1->pListNext;
  }
}
void BuildList(LIST * &head,int n)//
{
    //head=new LIST;
 LIST *p;
 LIST *q;
 p=head;
 head->a=0;
 for(int i=1;i<n+1;i++)
 {  
  q=new LIST;//作为新的结点
  p->pListNext=q;
  p=p->pListNext;//p指针后移一位
  p->a=i;//注意入在循环的最后面
 }
 p->pListNext=NULL;//最后一个节点的指针指向空
}
void RevertList(LIST * &head)
{
 LIST  *p=head;
    head=NULL;
 LIST *s;
 while(p)
 {
  s=p;//S是每次摘出的结点
  p=p->pListNext;//下移一个结点
  s->pListNext=head;
  head=s;//相当于head前移一个结点
 }
 
}

逆序的思路:

从原链表的头结点开始,摘除一个结点作为新链表的最后一个结点。

转载于:https://www.cnblogs.com/ddx-deng/archive/2012/12/16/3755865.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值