单链表的反转 c++

来源:互联网 发布:杨幂 知乎 编辑:程序博客网 时间:2024/04/29 13:11

#include<iostream>
#include<stdexcept>
using namespace std;
const int N=10;
typedef struct node
{ int key;
  struct node*next;
} NODE;
// INSERT A ELEMENT INTO A LINKLIST
bool insert(NODE*p,int position,int key)//insert an elemnt which will be the position-th element of the linklist;if fail to insert an element return false otherwise return true;position:1,2,3~~~~~~~

{  if(NULL==p)
    {cout<<"the linklist do not exist!";
    return false;
    }
   else
   {
   int i=0;
   NODE*p_find=p;//we will insert a new node following the node which is pointed by f_find
   NODE*p_new=NULL;
   while((i<position-1)&&p_find->next!=NULL)
         { p_find=p_find->next;
           ++i;
         }
   if(i!=position-1)// indicate that fail to find the position!
     return false;
   else
   {   try
         { p_new=new NODE;
         }       
      catch(bad_alloc)
        { cout<<"There is not enough memory to be allocated"<<endl;
          return false;
        }
      p_new->key=key;
      p_new->next=p_find->next;
      p_find->next=p_new;
      return true;
   }
   
   }
}
NODE*create_empty_linklist() //create a new empty linklist
{  NODE*p=NULL;
   try{p=new NODE;
      }
   catch(bad_alloc)
   { cout<<"there is no enough memory to be allocated ";
     return NULL;
   }
   p->next=NULL;
   return p;
}
void free_all_linklist(NODE*p)// free all the node in a linklist
{  NODE*pp=NULL;
   while(p!=NULL)
    { pp=p->next;
      delete p;
      p=pp;
    }
}
/************反转链表的程序************************/
/************反转链表的程序************************/
void reverse_linklist(NODE*p)// reverse a linklist; example:from  head_node->1->2->3->4   to  head_node->4->3->2->1

{  if(NULL!=p)
     {  NODE*p1=NULL,// 指向要反转的节点的前一个node,初始化必须为NULL;因为第一个节点的next域应该为NULL
        *p2=p->next,//要反转的node,p2被初始化为链表的第一个节点
        *p_save=NULL;//保存指向要反转的node的下一个节点的指针,因为反转后链表断裂,若不保存无法继续迭代
        while(NULL!=p2)
        { p_save=p2->next;
          p2->next=p1;//反转指针
          p1=p2;//移动p1
          p2=p_save;
        }
         p->next=p1;//头节点指向原来的尾元素
    }
    else
    throw runtime_error("the linklist needed to be reversed is NULL!");
}
/************反转链表的程序************************/
/************反转链表的程序************************/
void iter_print(const NODE*head)//打印链表
{ const NODE*p=head->next;
  while(p!=NULL)
       {cout<<p->key<<"  ";
        p=p->next;
       }
       cout<<endl;
}
int main(void)
{  int a[N]={1,2,3,4,5,5,5,6,7,7},
       i=0;
   NODE*head=create_empty_linklist();
   for(;i<N;++i)
      insert(head,1,a[i]);
      iter_print(head);
      reverse_linklist(head);
      iter_print(head);
      free_all_linklist(head);
      return 0;
      
}

原创粉丝点击