单链表原地反转

编写一个非递归过程以O(N)时间反转单链表
#include <iostream>
#include "./List.h"//利用我们自己实现的单链表List
using namespace std;
void PrintList(List L)
{
     if(NULL == L) return;
     Position pos = First(L);
     cout<<"List L:";
     while(NULL != pos)
     {
          cout<<Retrieve(pos)<<"->";
          pos = pos->next;
     }
     cout<<"NULL"<<endl;;
}
void ReverseListInPlace(List list)//使用头插法原地反转
{
     if(NULL == list) return ;
     Position pos = First(list);
     list->next = NULL;
     while(NULL != pos)
     {
          Position tmp = pos->next;
          pos->next = list->next;
          list->next = pos;
          pos = tmp;
     }
}
int main(int argc, char const *argv[])
{
     List l = CreateEmptyList();
     for(int i = 0; i != 10; ++i)
          PushBack(i, l);
     cout<<"Before reverse the list:";
     PrintList(l);
     cout<<endl;
     ReverseListInPlace(l);
     cout<<"After reverse the list:";
     PrintList(l);
     cout<<endl;
     return 0;
}

  

posted @ 2013-07-17 11:58  老司机  阅读(895)  评论(1编辑  收藏  举报