C++实现单链表逆序

2014-11-01 08:45:05 · 作者: · 浏览: 72

  将一个单链表逆序:


  struct list_node


  {


  list_node(int a,list_node* b):data(a),next(b) //这个为了测试方便


  {}


  int data;


  list_node* next;


  };


  void reserve(list_node* phead)


  {


  list_node* p = phead->next;


  if(p == NULL || p->next == NULL) return; //只有头节点或一个节点


  list_node* p1=p->next;


  p->next=NULL;


  while(p1!=NULL)


  {


  p = p1->next;


  p1->next = phead->next;


  phead->next = p1;


  p1 = p;


  }


  }


  测试程序:


  list lt;


  lt.phead = new list_node(0,0);


  lt.phead->next = new list_node(1,0);


  lt.phead->next->next = new list_node(2,0);


  lt.phead->next->next->next = new list_node(3,0);


  lt.reserve();


  list_node * p = lt.phead;


  while(p)


  {


  cout next;


  }


  编辑特别推荐: