从尾到头打印链表

来源:互联网 发布:阿波罗登月 知乎 编辑:程序博客网 时间:2024/06/14 14:09

首先想到是改变链表结构,使其从尾指向头

逆序链表:

 ListNode* ListReverse(ListNode *head){
    if(head==NULL||head->next==NULL) return head;
    ListNode *p->next=head;
    ListNode *current,*pre=head;
    current=pre->next;
    while(current){
    pre->next=current->next;
    current->next=p->next;
    p->next=current;
    current=pre->next;
    }
    return p->next;
}

但是当面试官不允许改变链表结构时,我们通过仔细理解题目,

从头到尾打印链表,意味着先进后出,所以可以使用栈结构

vector<int> ListReverse(ListNode *head){

    std::stack<ListNode*> s;

    vector<int> res;

    if(head==NULL) return res;

    ListNode *p=head;   

    if(p!=NULL){

      s.push(p);

      p=p->next;

     }

     while(!s.empty()){

      p=s.top();

      res.push_back(p->val);

      s.pop();

     }

     return res;}

既然想到了用栈来实现,而递归本质上也是一种栈

 vector<int> ListReverse(ListNode *head){

    vector<int> res;

    if(head==NULL) return res;

    ListNode *p=head;

    if(p){

      if(p->next)

          ListReverse(p->next);

      res.push_back(p->val);

     }

     return res;

  }

 
原创粉丝点击