1511:从尾到头打印链表 @jobdu

题目1511:从尾到头打印链表

时间限制:1 秒

内存限制:128 兆

特殊判题:

提交:1311

解决:440

题目描述:

输入一个链表,从尾到头打印链表每个节点的值。

输入:

每个输入文件仅包含一组测试样例。
每一组测试案例包含多行,每行一个大于0的整数,代表一个链表的节点。第一行是链表第一个节点的值,依次类推。当输入到-1时代表链表输入完毕。-1本身不属于链表。

输出:

对应每个测试案例,以从尾到头的顺序输出链表每个节点的值,每个值占一行。

样例输入:
1
2
3
4
5
-1
样例输出:
5
4
3
2
1

发现如果用递归来做会通不过最后一组测试,所以还是用了Stack



import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Stack;



public class S5 {

	public static void main(String[] args) throws FileNotFoundException {
		BufferedInputStream in = new BufferedInputStream(new FileInputStream("S5.in"));
        System.setIn(in);
		Scanner cin = new Scanner(System.in);
		ListNode head = null;
		ListNode tail = null;
		Stack<Integer> stack = new Stack<Integer>();
		
		while (cin.hasNextInt()) {
			int input = cin.nextInt();
			if(input == -1){
				break;
			}
			if(head == null){
				head = new ListNode(input);
				tail = head;
			}else{
				tail.next = new ListNode(input);
				tail = tail.next;
			}
			stack.add(input);
		}
		
//		printout(head);
//		reverseLinkedList(head);
		reverseLinkedListStack(stack);
	}
	
	public static void reverseLinkedList(ListNode head){
		if(head == null){
			return;
		}
		reverseLinkedList(head.next);
		System.out.println(head.val);
	}
	
	public static void reverseLinkedListStack(Stack stack){
		while(!stack.isEmpty()){
			System.out.println(stack.pop());
		}
	}
	
	public static void printout(ListNode head){
		while(head != null){
			System.out.println(head.val);
			head = head.next;
		}
	}
	
	public static class ListNode {
		public int val;
		public ListNode next;

		public ListNode(int x) {
			val = x;
			next = null;
		}
	}
	
}










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值