剑指offer 从尾到头打印单链表
问题描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
C++代码实现
初始化三个指针:*p = nullptr, *q = head, *r = nullptr。方法如下图所示:
class Solution {
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> arrayList;
ListNode *p = nullptr;
ListNode *r, *q;
q = head;
while(q)
{
r = q->next;
q->next=p;
p = q;
q = r;
}
head = p;
while(p)
{
arrayList.push_back(p->val);
p = p->next;
}
return arrayList;
}
};
python2代码实现
使用list列表用作栈,当然c++实现也可以使用栈的思想
append(obj),obj:插入的元素。函数将元素从尾部插入。
pop([index=-1]),obj:可选参数,要移除列表元素的索引值,不能超过列表总长度,默认为 index=-1,删除最后一个列表值。
# -*- coding:utf-8 -*-
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
arrayList = []
temp = []
while listNode:
temp.append(listNode.val)
listNode = listNode.next
while temp:
arrayList.append(temp.pop())
return arrayList
java代码实现
使用java的栈,不要忘记导入栈模块。
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.Stack;
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<Integer> sc = new Stack<Integer>();
while(listNode != null)
{
sc.push(listNode.val);
listNode = listNode.next;
}
ArrayList<Integer> arrayList = new ArrayList<Integer>();
while(!sc.empty())
{
arrayList.add(sc.pop());
}
return arrayList;
}
}