單鏈表面試題(二)從頭到尾打印單鏈表

  單鏈表面試題幾乎是面試的必考之題;

  對於單鏈表從頭到尾打印與單鏈表的逆置不是一回事。

  單鏈表的從頭到尾打印是打印出鏈表的數據。(即數據是從尾向前輸出);

  wKiom1eQRFPwDIBHAACSi89GA5Q684.png-wh_50


一、單鏈表從頭到尾打印:

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(struct ListNode* head) {
         vector<int> result;
         stack< ListNode*> node;
             struct ListNode* newhead=head;
             while(newhead!=NULL)
             {
             node.push(newhead);
             newhead=newhead->next;
         }
        while(!node.empty())
            {
            newhead=node.top();
            result.push_back(newhead->val);
            node.pop();
        }
        return result;
    }
         
};

二、單鏈表的逆置

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
             if(pHead==NULL)
                 return NULL;
           ListNode* cur=pHead;
           ListNode* newHead=NULL;
        while(cur)
            {
            ListNode* tmp=cur;
            cur=cur->next;
            tmp->next=newHead;
            newHead=tmp;
        }
        return newHead;
            
    }
};


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