【剑指offer】面试题6:从头到尾打印链表
2017-07-13 01:07
489 查看
完整代码地址
完整代码地址题目
输入一个链表,从尾到头打印链表每个节点的值。链表节点的定义如下: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); }
相关文章推荐
- 剑指offer 面试题5——从头到尾打印链表
- 剑指offer面试题5 从头到尾打印链表(java)
- 剑指Offer-【面试题05:从头到尾打印链表】
- 剑指offer--面试题6:从头到尾打印链表
- 剑指offer面试题5 从头到尾打印链表(java)
- 剑指offer-面试题05-从尾到头打印链表
- 【剑指Offer面试题】 九度OJ1511:从尾到头打印链表
- 剑指offer面试题5—反向打印链表
- 剑指offer:Java实现从头到尾打印链表
- 剑指Offer面试题12打印1到最大的n位数,面试题13在O(1)时间删除链表结点
- 【剑指offer】面试题5:从尾到头打印链表
- 剑指offer 面试题5:从尾到头打印链表
- 剑指Offer面试题5:从尾到头打印链表
- 【练习笔记】剑指offer-面试题5 :从尾到头打印链表
- half ok剑指Offer面试题6 从尾到头打印链表
- 剑指offer-从头到尾打印链表
- [剑指offer]面试题5:从尾到头打印链表
- [牛客网,剑指offer,python] 从头到尾打印链表