算法設計與分析01-鏈表的逆置

一.最常用的方法:

LNode*  ReverseList(LNode* head)
{
    if (head == NULL)
        return NULL;
    if (head->next == NULL)
        return head;
    LNode* pre = NULL;
    LNode* Cur = head;
    LNode* Nex = NULL;
    while (Cur!=NULL)
    {
        Nex = Cur->next;
        Cur->next = pre;
        pre = Cur;
        Cur = Nex;
    }
    return pre;
}
二.利用遞歸方法:

LNode* ReverList1(LNode* head)
{
    if (head == NULL)
        return NULL;
    if (head->next == NULL)
    {
        return head;
    }
    LNode* Node = head; //保留上一個結點
    LNode* Nex = head->next;
    LNode* HeadNode = ReverList1(Nex);
    Nex->next = Node; //逆置
    Node->next = NULL; //這句必須有,否則會產生循環鏈表
    return HeadNode;//返回逆置鏈表的尾結點
    
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章