单链表的逆置

剑指offer 从尾到头打印单链表

问题描述

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

来源:牛客网
链接:https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035?tpId=13&tqId=11156&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

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;
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值