链表的创建、逆序等操作

#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前移一个结点
 }
 
}

逆序的思路:

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

posted @ 2012-12-16 20:59  deeeeeed  阅读(121)  评论(0编辑  收藏  举报

pppppppppppppp