倒序输出单链表

倒序输出的方式有两种,

1、用arrayList,node.next=null的时候开始add。

2、用栈的后进先出。


程序倒是不难,不过编译的时候报了这个错:


No enclosing instance of type E is accessible. Must qualify the allocation with an enclosing instance of type E(e.g.  x.new A() where x is an instance of E). 

这个我百度了一下,

【http://blog.csdn.net/sunny2038/article/details/6926079】

长见识了~要用static~~ 之前在书上看到过这种错误的描述,但是真的出了错,根本想不到这个点儿。

看来实践出真知,果然不错。


/**
 * 
 */
package dianer;

import java.util.Scanner;
import java.util.Stack;

/** 
* * @author LilyLee
 * @date  2017年3月19日
 * @Version 
 *题目:
 *输入一个链表,从尾到头打印链表每个节点的值。
 */

/*
 * 这个题有两个解法,
 * 1、用递归,递归到next=null的时候开始add arrayList。
 * 2、用栈实现(感觉跟1差不多),用栈的后进先出。
 * 所以就用栈做这个题吧,反正我感觉都差不多。
 * */
public class printListFromTailToHead {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();

		int[] num = new int[n];
		for (int i = 0; i < n; i++) {
			num[i] = in.nextInt();
		}
		ListNode node = createNode(n, num);
		PrintList(node);

	}
	
	public static void PrintList(ListNode Listnode){
			Stack<Integer> stack=new Stack<Integer>();
			while(Listnode!=null){
				stack.push(Listnode.value);
				Listnode=Listnode.next;
			}
			while(!stack.isEmpty()){
				System.out.print(stack.pop()+" ");
			}
		
	}
	
	
	
	public static ListNode createNode(int n, int[] num) {
		ListNode head = null;
		
		if (n <= 0) {
			System.out.println("error"); return head;
		}
		
		ListNode aListNode = new ListNode(num[0]);
		head = aListNode;
		
		for (int j = 1; j < n; j++) {
			aListNode.next = new ListNode(num[j]);
			aListNode = aListNode.next;
		}
		return head;
	}
	
	static class ListNode {
		int value;
		ListNode next;
		public  ListNode(int value) {
			this.value=value;
		}
}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值