• (剑指Offer)面试题5:从尾到头打印链表


    题目:

    输入一个链表的头结点,从尾到头反过来打印每个结点的值。

    链表结点定义:

    struct ListNode{
        int value;
        ListNode* pNext;
    };

    思路:

    1、改变链表结构的话,先反转链表,然后从头到尾打印每个结点的值。(后续博文会有相关实现,这里就暂不实现)

    2、无需改变链表结构,使用栈,遍历整个链表,将结点依次入栈,然后再依次出栈,实现“后进先出”。

    3、无需改变链表结构,递归实现,如果链表结点数过多的话,可能会导致栈溢出。

    代码:

    void PrintListReversingly_Iteratively(ListNode* pHead){
        std::stack<ListNode*> nodes;
        ListNode* pNode=pHead;
        while(pNode!=NULL){
            nodes.push(pNode);
            pNode=pNode->pNext;
        }
        while(!nodes.empty()){
            pNode=nodes.top();
            cout<<pNode->value<<"	";
            nodes.pop();
        }
        cout<<endl;
    }
    
    void PrintListReversingly_Recursively_1(ListNode* pHead){
        if(pHead==NULL)
            return;
        PrintListReversingly_Recursively_1(pHead->pNext);
        cout<<pHead->value<<"	";
    }
    
    void PrintListReversingly_Recursively_2(ListNode* pHead){
        if(pHead!=NULL){
            if(pHead->pNext!=NULL)
                PrintListReversingly_Recursively_2(pHead->pNext);
            cout<<pHead->value<<"	";
        }
    }
    

    在线测试OJ:

    http://www.nowcoder.com/books/coding-interviews/d0267f7f55b3412ba93bd35cfa8e8035?rp=1

    AC代码:

    /**
    *  struct ListNode {
    *	    int val;
    *	    struct ListNode *next;
    *	    ListNode(int x) :
    *			  val(x), next(NULL) {
    *	    }
    *  };
    */
    class Solution {
    public:
        void printList(ListNode* head,vector<int> &nodes){
            if(head!=NULL){
                printList(head->next,nodes);
                nodes.push_back(head->val);
            }
            return;
        }
    	vector<int> printListFromTailToHead(struct ListNode* head) {
            vector<int> nodes;
    		printList(head,nodes);
            return nodes;
    	}
    };
    
    /**
    *  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> nodes;
            while(head!=NULL){
                nodes.push_back(head->val);
                head=head->next;
            }
            reverse(nodes.begin(),nodes.end());
            return nodes;
    	}
    };
    

      

  • 相关阅读:
    无废话WCF入门教程六[一个简单的Demo]
    MVC分页
    用于查询的日期类型转换帮助类
    无废话SharePoint入门教程五[创建SharePoint页面布局]
    一天内“被喷”7.5小时后感
    无废话SharePoint入门教程四[创建SharePoint母版页]
    无废话SharePoint入门教程三[创建网站集和网站]
    无废话SharePoint入门教程二[SharePoint发展、工具及术语]
    MTK USER版本禁止log输出
    MTK 音量加减键修改为默认控制媒体音量
  • 原文地址:https://www.cnblogs.com/AndyJee/p/4624417.html
Copyright © 2020-2023  润新知