单链表,实现逆转

来源:互联网 发布:john frusciante 知乎 编辑:程序博客网 时间:2024/05/18 00:55

 #include <iostream>
using namespace std;

#include <cassert>

struct node
{
 int  data;
 node * next;
public:
 node(int d, node* n)
 {
  data = d;
  next = n;
 }
};

class  list
{
public:
 list( );
 virtual ~list( );
public:
 void insert(int data);
 void reverse();

 void print();

private:
 node * head;
};

list::list(): head(0)
{

}

list::~list( )
{
 head = 0;
}

void list::insert(int  data)
{
 node * pNewNode = new node(data, head);
 head = pNewNode; 
}

void list::print()
{
 node * pNode = head;
 while (pNode)
 {
  cout << pNode->data << " ";
  pNode = pNode->next;
 }
}

void list::reverse()
{
 if ( !head )
  return;

 node * p1 = head;
 node * p2 = head->next;
 while (p2)
 {
  node * temp = p2->next;
  p2->next = p1;
  p1 = p2;
  p2 = temp;
 }
 head->next = 0;
 head = p1;
}

 

int main( )
{
 list  testList;
 for ( int n = 0; n < 10; n ++ )
 {
  testList.insert(n);
 }

 testList.print();
 cout << endl;

 testList.reverse();

 testList.print();
 cout << endl;

 return 0;
}