剑指Offer学习之面试题5 : 从尾到头打印链表
2017-05-27 22:25
555 查看
题目:输入个链表的头结点,从尾到头反过来打印出每个结点的值。
package com.www.OfferToSword;
import java.util.Stack;
public class Solution5 {
public static class ListNode {
int val;
ListNode next;
}
/**
* 输入个链表的头结点,从尾到头反过来打印出每个结点的值 使用栈的方式进行
*
* @param root
* 链表头结点
*/
public static void printListInversilyUsingIteration(ListNode root) {
Stack<ListNode> stack = new Stack<>();
while (root != null) {
stack.push(root);
root = root.next;
}
ListNode tmp;
while (!stack.isEmpty()) {
tmp = stack.pop();
System.out.print(tmp.val + " ");
}
}
/**
* 输入个链表的头结点,从尾到头反过来打印出每个结点的值 使用栈的方式进行
*
* @param root
* 链表头结点
*/
public static void printListInverselyUsingRecursion(ListNode root) {
if (root != null) {
printListInverselyUsingRecursion(root.next);
System.out.print(root.val + " ");
}
}
public static void main(String[] args) {
ListNode root = new ListNode();
root.val = 1;
root.next = new ListNode();
root.next.val = 2;
root.next.next = new ListNode();
root.next.next.val = 3;
root.next.next.next = new ListNode();
root.next.next.next.val = 4;
root.next.next.next.next = new ListNode();
root.next.next.next.next.val = 5;
printListInversilyUsingIteration(root);
// System.out.println();
// printListInverselyUsingRecursion(root);
}
}
package com.www.OfferToSword;
import java.util.Stack;
public class Solution5 {
public static class ListNode {
int val;
ListNode next;
}
/**
* 输入个链表的头结点,从尾到头反过来打印出每个结点的值 使用栈的方式进行
*
* @param root
* 链表头结点
*/
public static void printListInversilyUsingIteration(ListNode root) {
Stack<ListNode> stack = new Stack<>();
while (root != null) {
stack.push(root);
root = root.next;
}
ListNode tmp;
while (!stack.isEmpty()) {
tmp = stack.pop();
System.out.print(tmp.val + " ");
}
}
/**
* 输入个链表的头结点,从尾到头反过来打印出每个结点的值 使用栈的方式进行
*
* @param root
* 链表头结点
*/
public static void printListInverselyUsingRecursion(ListNode root) {
if (root != null) {
printListInverselyUsingRecursion(root.next);
System.out.print(root.val + " ");
}
}
public static void main(String[] args) {
ListNode root = new ListNode();
root.val = 1;
root.next = new ListNode();
root.next.val = 2;
root.next.next = new ListNode();
root.next.next.val = 3;
root.next.next.next = new ListNode();
root.next.next.next.val = 4;
root.next.next.next.next = new ListNode();
root.next.next.next.next.val = 5;
printListInversilyUsingIteration(root);
// System.out.println();
// printListInverselyUsingRecursion(root);
}
}
相关文章推荐
- 《剑指Offer》学习笔记--面试题5:从尾到头打印链表
- (剑指Offer)面试题5:从尾到头打印链表
- 剑指offer 面试题5 从尾到头打印链表
- 剑指Offer: 面试题5 从尾到头打印链表
- 剑指Offer系列-面试题5:从尾到头打印链表
- 《剑指offer》面试题5—从尾到头打印链表
- 【剑指Offer学习】【面试题5 : 从尾到头打印链表】
- 《剑指Offer》面试题五之从尾到头打印链表
- 剑指Offer学习总结-从尾到头打印链表
- 剑指Offer面试题5[从尾到头打印链表]
- 剑指offer面试题5——链表之从尾到头打印链表
- 剑指offer-面试题5.从尾到头打印链表
- 剑指offer--面试题5:从尾到头打印链表--Java实现
- 剑指offer面试题5:从尾到头打印链表
- 《剑指offer》Python语言 面试题5:从尾到头打印链表
- 《剑指Offer》面试题:从尾到头打印链表
- 剑指offer之面试题5:从尾到头打印链表
- [剑指offer学习心得]之:从尾到头打印链表
- 《剑指offer》面试题5:从尾到头打印链表
- 剑指offer面试题[5]-从尾到头打印链表