將一個單向鏈表逆序


/*
*about: 騰訊面試,將一個單向鏈表逆序
*author:justinzhang
*email:uestczhangchao@gmail.com
*estblished:2011年4月24日16:40:25
*revised:2011年5月10日15:00:26
*/

#include <iostream>
using namespace std;

class node
{
      public:
      node * next;
      int data;
};


node *test = NULL;

node *nodereverse(node *head)
{
    //如果一個函數的輸入參數有指針,一定要記住判斷指針時候為空
    //1>:在使用一個指針之前一定要判斷它是否為空;
    //2>:使用完后要釋放由指針指向的存儲單元
    //3>:釋放完存儲單元后要將指針賦值為NULL;
     if(head->next==NULL || head==NULL)
          return head;

     node* temp1=head;
     node* temp2=NULL;
     node* temp3=head->next;
     temp1->next = NULL;
     //要注意這里面的順序,先將temp3保存在temp2中,
     //然后再將temp3移動到下一個元素,然后才能改動temp2
     //
     while(temp3->next!=NULL)
     {
        temp2 = temp3;
        temp3 = temp3->next;
        temp2->next = temp1;//不能再temp3= temp3->next;之前執行
        temp1 = temp2;

     }
     temp3->next = temp2;
     return temp3;
}
void initnode()
{
     node * tmp = NULL;
     for(int i=0; i<4; i++)
     {
         tmp = new node;
         tmp->data = i;
         tmp->next = test;
         test = tmp;
     }
}

void display(node *nn)
{
if(nn==NULL)
{
    cout << "no data to display\n";
    return ;
}
node *dis = nn;
 while(dis!=NULL)
 {
        cout << dis->data << endl;
        dis = dis->next;
 }
}

//釋放動態申請的空間
void distroy(node *nn)
{
    if (nn==NULL)
    {
        return ;
    }
    while (nn!=NULL)
    {
        node *tmp = nn;
        nn = nn->next;
        delete tmp;
    }
}


int main()
{
    initnode();
    display(test);
    cout << "**************" << endl;
    node *tmp = nodereverse(test);
    if(test==NULL)
        exit(0);
    display(tmp);
    //tmp和test指向的存儲空間已經使用完畢,應該釋放掉他們申請的空間!
    //並且,要將他們賦值為NULL,否則他們將成為野指針!!!!,一定要注意了~~
    distroy(tmp);//釋放動態申請的內存
    tmp = NULL;//將他們重新賦值為NULL,不然就會成為野指針~~~~~
    test = NULL;
    cout << "tmp= " << tmp << endl;

    //如果上面沒有tmp = NULL;test = NULL;,display將會出錯,
    //因為在display開始的時候判斷傳入的參數是否為NULL,如果不把野指針賦值為NULL,
    //那么判斷就沒有效果,會繼續指向display中的while語句,而此時指針所指向的存儲空間已經被釋放掉了,
    //這樣就會出現異常.
    display(test);
    system("pause");
    return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM