剑指offer-5:从头到尾打印链表

package listTest.printList;
/**
 * 题目:输入一个链表的头结点,从尾到头反过来打印出每个结点的值。
 * 常规思路:把链表中链接结点的指针反转过来,改变链表的方向,然后从头到尾打印。但是这样改变原来链表的结构。
 *        要清楚题目要求是否可以改变链表的结构。
 * 第二种思路:遍历链表,遍历的顺序是从头到尾,可是输出的顺序是从尾到头。“后进先出”,栈!!!
 *        每经过一个结点的时候,把该结点放到一个栈中。当遍历完整个链表后,再从栈顶开始逐个输出结点的值,
 *        此时输出结点的顺序已经反转过来了。
 * 第三种思路:递归,在本质上就是一个栈结构。
 */
import java.util.Stack;

public class PrintListTest {

	//方法一:辅助栈
	private void printList(ListNode head) {
		
        ListNode pNode = head;
		Stack<ListNode> stack = new Stack<ListNode>();
		
		//将链表结点依次遍历入栈
		while(pNode!=null) {
			stack.push(pNode);
			pNode = pNode.next;
		}
		
		//依次查询栈顶元素的值,出栈
		while(!stack.empty()) {
			pNode = stack.peek();
			System.out.println(pNode.data);
			stack.pop();
		}
	}
	
	//方法二:递归调用
	//每访问到一个节点的时候,先递归输出他后面的结点,再输出该节点自身,这样链表的输出结果就反过来了,
	public void printListTest(ListNode head) {
		if(head!=null) {
			if(head.next!=null) {
				printListTest(head.next);
			}
			System.out.println(head.data);
		}
	}
	
	//测试的main()
	public static void main(String args[]) {
		ListNode node = new ListNode("aaa");
		ListNode head = node;
		
		ListNode one = new ListNode("hello");
		node.next = one;
		
		ListNode two = new ListNode("world");
		one.next = two;
		
		ListNode three = new ListNode("name");
		two.next = three;
		
		PrintListTest t = new PrintListTest();
//		t.printList(head);
		t.printListTest(head);
	}
}

结点类:

package listTest.printList;

/**
 * 
 * @author summ
 *
 */
public class ListNode {
	
	String data;
	
	ListNode next;
	
	
	public ListNode(String string) {
		this.data = string;
	}
	
	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}


	public ListNode getNext() {
		return next;
	}
	public void setNext(ListNode next) {
		this.next = next;
	}
	
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值