温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-07-26 15:25:27 来源:网络 阅读:556 作者:菜鸟笔记 栏目:编程语言

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

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

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

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


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

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


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI