反轉鏈表

第一種:

class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {

        if(pHead==NULL) 
        return NULL; 
        ListNode* pNode=pHead; //當前指針
        ListNode* pReverseHead=NULL; //新鏈表的頭指針
        ListNode* pPrev=NULL;  //當前指針的前一個結點

        while(pNode!=NULL) //當前結點不爲空時才執行
       {
        ListNode* pNext=pNode->next;//鏈斷開之前一定要保存斷開位置後邊的結點
        if(pNext==NULL)//當pNext爲空時,說明當前結點爲尾節點
        pReverseHead=pNode;
        pNode->next=pPrev;//指針反轉
        pPrev=pNode;
        pNode=pNext;
      }
        return pReverseHead;
    }
}

第二種:

class Solution {
public:
  ListNode* ReverseList(ListNode* pHead)//如果鏈表爲空或者鏈表中只有一個元素  
  {
    if(pHead==NULL||pHead->next==NULL) return pHead;
     //先反轉後面的鏈表,走到鏈表的末端結點
    ListNode* pReverseNode=ReverseList(pHead->next);
     //再將當前節點設置爲後面節點的後續節點
        pHead->next->next=pHead;
        pHead->next=NULL;
        return pReverseNode;  
    }
};
發佈了49 篇原創文章 · 獲贊 28 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章