#数据结构与算法学习笔记#剑指Offer3:从尾到头打印链表(Java、C/C++)

2018.7.29

题目描述

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

JAVA实现:

/**
 * 
 * @author ChopinXBP
 * 输入一个链表,从尾到头打印链表每个节点的值。
 * 思路:压入栈
 *
 */
import java.util.Stack;
import java.util.ArrayList;


class ListNode {
	int val;
	ListNode next = null;

	ListNode(int val) {
		this.val = val;
	}
}

public class printListFromTailToHead_3 {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        Stack<Integer> stack = new Stack<>();
        while (listNode != null) {
            stack.push(listNode.val);
            listNode = listNode.next;
        }
 
        ArrayList<Integer> list = new ArrayList<>();
        while (!stack.isEmpty()) {
            list.add(stack.pop());
        }
        return list;       
    }
}

C++实现:

/*
* 输入一个链表,从尾到头打印链表每个节点的值。
*/

#include "stdafx.h"
#include <vector>
#include <stack>
using namespace std;

/*


最佳解答1:压入栈

class Solution
{
public:
	vector<int> printListFromTailToHead(ListNode* head)
	{
		vector <int>  result;
		stack<int> arr;
		ListNode* p = head;
		while (p != NULL)
		{
			arr.push(p->val);
			p = p->next;
		}
		int len = arr.size();
		for (int i = 0; i<len; i++)
		{
			result.push_back(arr.top());
			arr.pop();
		}
		return  result;
	}

};


最佳解答2:不断前插

class Solution {
public:
	vector<int> printListFromTailToHead(ListNode* head) {
		vector<int> value;
		if (head != NULL)
		{
			value.insert(value.begin(), head->val);
			while (head->next != NULL)
			{
				value.insert(value.begin(), head->next->val);
				head = head->next;
			}

		}
		return value;
	}
};
*/



  struct ListNode {
        int val;
        struct ListNode *next;
        ListNode(int x) :
              val(x), next(NULL) {
        }
  };

class Solution {
public:
	vector<int> printListFromTailToHead(ListNode* head) {
		vector<int> data;
		if (head == NULL || head->next == NULL)return data;

		ListNode*p = head;
		int q[100];
		int count = 0;

		while (p->next != NULL){
			q[count] = p->val;
			p = p->next;
			count++;
		}
		q[count] = p->val;

		for (int i = count; i >= 0; i--){
			data.push_back(q[i]);
		}

		return data;		
	}
};

猜你喜欢

转载自blog.csdn.net/qq_20304723/article/details/81271234