题目描述
输入一个链表,从尾到头打印链表每个节点的值。
输入描述:
输入为链表的表头
输出描述:
输出为需要打印的“新链表”的表头
python实现:
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 法1:头插发。返回从尾部到头部的列表值序列,例如[1,2,3]
# 种种方法返回不满足牛客网OJ的格式只是复习一下“头插法”
def printListFromTailToHead1(self, listNode):
# write code here
#头插法reverse链表,但是修改了原链表,不合适
if listNode is None or listNode.next is None:
return listNode
helper = ListNode(0)
helper.next = ListNode
p = ListNode
while p:
q = p.next
p.next = helper.next
helper.next = p
p = q
return helper.next
#法2:不修改原链表,使用栈
def printListFromTailToHead2(self, listNode):
if listNode is None:
return []
p = listNode
stack = []
while p:
stack.append(p.val)
p = p.next
stack.reverse()
return stack
#法3:递归
def printListFromTailToHead(self, listNode): # 递归法
# write code here
if listNode is None:
return []
result = self.printListFromTailToHead(listNode.next)
result.append(listNode.val)
return result
c++实现:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
//法1:使用栈
vector<int> printListFromTailToHead1(struct ListNode* head) {
vector<int> myStack;
ListNode *p = head;
while(p!=NULL){
myStack.push_back(p->val);
p = p->next;
}
reverse(myStack.begin(), myStack.end());
return myStack;
}
//法2:递归
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> myStack;
if(head){
if(head->next)
myStack = printListFromTailToHead(head->next);
myStack.push_back(head->val);
}
return myStack;
}
};