从尾到头打印链表

从尾到头打印链表

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

版本一: 没什么技术含量, 利用vector数组简单交换头尾数子

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> ret;
        ListNode *current = head;
        int low = 0;
        int high = 0;
        
        if (NULL == head) {
            return ret;
        }
        
        while (NULL != current) {
            ret.push_back(current->val);
            current = current->next;
        }
        
        high = ret.size() - 1;
        
        while (low < high) {
            ret[low] = ret[low] + ret[high];
            ret[high] = ret[low] - ret[high];
            ret[low] = ret[low] - ret[high];
            low++;
            high--;
        }
        
        return ret;
    }
};

版本二: 利用栈的先进后出的思想来交换头尾数字

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        stack<int> sk;
        vector<int> ret;
        ListNode *current = head;
        
        while(NULL == head) {
            return ret;
        }
        
        while(NULL != current) {
            sk.push(current->val);
            current = current->next;
        }
        
        while(!sk.empty()) {
            ret.push_back(sk.top());
            sk.pop();
        }
        return ret;
    }
};

版本三: 利用递归, 源自牛客网

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> dev;    
    vector<int> printListFromTailToHead(ListNode* head) {
        if(head!=NULL) {
          if(head->next!=NULL) {
            dev=printListFromTailToHead(head->next);
          }
          dev.push_back(head->val);
        }
        return dev;
    }
};

版本四: 自己在vs上写的, 不知道为何提交到牛客上不能通过

#include <iostream>
#include <stack>
#include <vector>

using namespace std;

struct ListNode {
	int val;
	struct ListNode *next;
};

vector<int> ret;

vector<int> printArray(ListNode* head, vector<int> &v) {
	if (NULL != head->next) {
		v = printArray(head->next, v);
	}

	v.push_back(head->val);
	//cout << head->val << endl;

	return v;
}

vector<int>& printListFromTailToHead(ListNode* head) {

	ret = printArray(head, ret);
	return ret;
}

void main(void) {
	ListNode n1, n2, n3;
	vector<int> ret;

	n1.val = 1, n2.val = 2, n3.val = 3;
	n1.next = &n2;
	n2.next = &n3;
	n3.next = NULL;

	ret = printListFromTailToHead(&n1);
	for (int i = 0; i < ret.size(); i++) {
		cout << ret[i] << endl;
	}
}
posted @ 2019-02-21 13:49  张飘扬  阅读(154)  评论(0编辑  收藏  举报