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

本文详细介绍了如何通过迭代和递归两种方式,从链表尾部开始打印每个结点的值。包括链表结点定义、核心思路和AC代码实现,并提供了在线测试链接。

题目:

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

链表结点定义:

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<<"\t";
        nodes.pop();
    }
    cout<<endl;
}

void PrintListReversingly_Recursively_1(ListNode* pHead){
    if(pHead==NULL)
        return;
    PrintListReversingly_Recursively_1(pHead->pNext);
    cout<<pHead->value<<"\t";
}

void PrintListReversingly_Recursively_2(ListNode* pHead){
    if(pHead!=NULL){
        if(pHead->pNext!=NULL)
            PrintListReversingly_Recursively_2(pHead->pNext);
        cout<<pHead->value<<"\t";
    }
}

在线测试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;
	}
};

  

转载于:https://www.cnblogs.com/AndyJee/p/4624417.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值