链表:从尾到头打印链表——剑指offer(牛客网 JZ3)

class Solution {
    /*思路:从尾到头打印链表,即逆序反转链表。
    使用三个指针,
    中间的pCur->next指向前面的pPre后,
    用赋值移动pPre、pCur和pNext,避免了链表断链导致的不能移动到下一步*/
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        ListNode *pPre = NULL;
        ListNode *pCur = pHead;//--pCur起始位置
        ListNode *pNext = NULL;
        while(pCur != NULL){
            pNext = pCur->next;//--中间的pCur->next指向前面的pPre
            pCur->next = pPre; //--用赋值移动pPre、pCur和pNext
            pPre = pCur;
            pCur = pNext;
        }
        
        vector<int> ret;//链表结果保存到vector中
        while(pPre != NULL){
            ret.push_back(pPre->val);
            
            pPre = pPre->next;
        }
        return ret;
    }
};
View Code

 

posted on 2021-03-10 17:44  平ping  阅读(25)  评论(0)    收藏  举报