【6. 从尾到头打印链表】剑指offer-JAVA实现

176 阅读1分钟

题目描述: 从尾到头反过来打印出每个结点的值。

思路1:头插法

代码:

public class Six {
	private Node first;
	public class Node{
		public int key;
		public Node next;
	}
	
	public Node createN(Node head) {
		Scanner in = new Scanner(System.in);
		while(in.hasNext()) {
		if(head==null) {
			head = new Node();
			head.key = in.nextInt() ;
			head.next = null;
		}else {
			Node newNode = new Node();
			newNode.key = in.nextInt();
			newNode.next = head;
			head=newNode;
	          }
		}
		return head;
	}
	
	
	public void printNode(Node n) {
		if(n==null)
			System.out.println("空链表");
		while(n!=null) {
			System.out.println(n.key);
			n = n.next;
			
		}

	}
	
	
}

思路2: 后进先出想到栈, 把链表放进栈中/尾插+扔进栈中在拿出来

代码:

		Stack<Integer> s = new Stack<>();
		public class Node{
			public int key;
			public Node next;
		}
		
		public Node createN(Node head,Node tailer) {
			
			Scanner in = new Scanner(System.in);
			while(in.hasNext()) {
			if(head==null) {
				head = new Node();
				head.key = in.nextInt();
				head.next = null;
				tailer = head;
			}else {
				Node newNode = new Node();
				newNode.key = in.nextInt();
				tailer.next = newNode;
				tailer = newNode;
				
			}
		}
			return head;
			
	}
		
		public void printN(Node head) {
			Stack<Integer> s = new Stack<>();
			while(head!=null) {
				s.add(head.key);
				head=head.next;
			}
			Stack<Integer> o = new Stack<>();
			while(!s.isEmpty())
				o.add(s.pop());
			Iterator it = o.iterator();
			while(it.hasNext())
				System.out.println(it.next());
		}
		 
}

总结: 1.头插法:

       newNode.next = head;
       head=newNode;

2.尾插法

       tailer.next = newNode;
       tailer = newNode;

3.递归本质是栈结构