【剑指offer】面试题6:从头到尾打印链表
来源:互联网 发布:巫师3上古卷轴5 知乎 编辑:程序博客网 时间:2024/05/22 07:48
完整代码地址
完整代码地址
题目
输入一个链表,从尾到头打印链表每个节点的值。链表节点的定义如下:
class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; }}
思路
方法1:放到LinkedList中再打印出来(一起入栈然后出栈)
方法2:遍历链表的时候将指针的指向反转(但是会修改输入的数据)
我们采用方法1实现
(提交代码忘了import java.util.Collections;给我挂了一次,心痛!!)
代码
public static class ListNode { int val; public ListNode next = null; public ListNode(int val) { this.val = val; }} public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> arrayList = new ArrayList<>(); ListNode current = listNode; while(current != null) { arrayList.add(current.val); current = current.next; } Collections.reverse(arrayList); return arrayList;}
测试
public static void main(String[] args) { test1(); test2();}/** * 功能测试 * 1.链表有多个节点 * 2.链表只有一个节点 */private static void test1() { ListNode head1 = new ListNode(1); ListNode node1 = new ListNode(2); ListNode node2 = new ListNode(3); ListNode node3 = new ListNode(4); head1.next = node1; node1.next = node2; node2.next = node3; ArrayList<Integer> arr1 = new ArrayList<>(Arrays.asList(4,3,2,1)); ArrayList<Integer> arr2 = _06_PrintListInReversedOrder.printListFromTailToHead(head1); MyTest.equal(arr1.equals(arr2), true); ListNode head2 = new ListNode(99); ArrayList<Integer> arr3 = new ArrayList<>(Arrays.asList(99)); ArrayList<Integer> arr4 = _06_PrintListInReversedOrder.printListFromTailToHead(head2); MyTest.equal(arr3.equals(arr4), true);}/** * 特殊输入测试 * 输入的链表头结点为null */private static void test2() { ArrayList<Integer> arrayList = new ArrayList<>(); ArrayList<Integer> arr2 = _06_PrintListInReversedOrder.printListFromTailToHead(null); MyTest.equal(arrayList.equals(arr2), true);}
阅读全文
0 0
- 剑指offer--面试题6:从头到尾打印链表
- 【剑指offer】面试题6:从头到尾打印链表
- 《剑指Offer》面试题-从头到尾打印链表
- 《剑指offer》面试题5从头到尾打印链表
- 剑指offer面试题之从头到尾打印链表
- 剑指offer面试题5 从头到尾打印链表(c)
- 剑指offer面试题5 从头到尾打印链表(java)
- 面试题5 从头到尾打印链表
- 面试题5 从头到尾打印链表
- 面试题5:从头到尾打印链表
- 面试题5:从头到尾打印链表
- [剑指offer]从头到尾打印链表
- 剑指offer-5:从头到尾打印链表
- 剑指Offer-从头到尾打印链表
- 剑指offer—从头到尾打印链表
- 剑指Offer---从头到尾打印链表
- 牛客网-剑指offer-从头到尾打印链表
- 剑指offer 从头到尾打印链表
- 查看linux系统发行版的命令
- 10 Three.js使用orbit controls插件(轨道控制)来控制模型交互动作
- JavaScript循环、JS HTML DOM、JS Window
- FFmpeg学习笔记-踩坑
- MYSQL存储引擎
- 【剑指offer】面试题6:从头到尾打印链表
- 35入坑!努力中!Eclipse maven svn安装!
- hibernate_持久化类、主键生成策略
- 终极方案:DCloud技术与androidstudio打包
- js_day01_js实现1到100的和为5050
- List接口
- 纯css样式实现盒子 3D 旋转、鼠标悬停效果
- 状态栏通知网络链接的情况(wifi 2g/3g/4g/无网络链接状态)
- PHP如何解决网站大流量与高并发的问题