单链表面试题(二)从头到尾打印单链表

2023-05-29,,

  单链表面试题几乎是面试的必考之题;

  对于单链表从头到尾打印与单链表的逆置不是一回事。

  单链表的从头到尾打印是打印出链表的数据。(即数据是从尾向前输出);

  

一、单链表从头到尾打印:

/**
*  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;
            
    }
};

《单链表面试题(二)从头到尾打印单链表.doc》

下载本文的Word格式文档,以方便收藏与打印。