码迷,mamicode.com
首页 > 其他好文 > 详细

从尾到头打印链表

时间:2017-03-09 18:18:07      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:目的   写法   pack   sys   rgs   从尾到头打印链表   his   turn   system   

本题目有两种实现思路,一种采用栈另外一种采用递归的方式进行实现。此题其实考察的目的在于java中链表的实现,此外此题还可以扩展到链表的插入删除,指定位置的插入以及删除,这个点以后再进行补充

package jianzhi_offer;

import java.util.Stack;

public class PrintListReversingly {
	public static  void PrintListReversingly(ListNode phead){
		//此时是按照栈的方式进行打印的,此时熟悉了链表的写法还有链表的构建,另外还可以采用递归的方式进行打印,方法见下面
		Stack<ListNode> stack = new Stack();
		while(phead!=null){
			stack.push(phead);
			phead=phead.next;
		}
		while(!stack.empty()){
			System.out.println(stack.pop().value);
		}
	}
	
	public static  void PrintListReversingly2(ListNode phead){
		//此时是按照栈的方式进行打印的,此时熟悉了链表的写法还有链表的构建,另外还可以采用递归的方式进行打印,方法见下面
		if(phead!=null){
			if(phead.next!=null){
				PrintListReversingly2(phead.next);	
				System.out.println(phead.value);
			}else{
				System.out.println(phead.value);
			}
		}
	}
	
	public static void main(String []args){
		ListNode node1=new ListNode(4);
		ListNode node2=new ListNode(3);
		ListNode node3=new ListNode(5);
		node1.next=node2;
		node2.next=node3;
		node3.next=null;
		
		PrintListReversingly(node1);
		PrintListReversingly2(node1);
		
		
	}

}

 

package jianzhi_offer;

public class ListNode<T> {
	T value;
	ListNode next;
	
	public ListNode(){
		this.value=value;
	}
	
	public ListNode(T value){
		this.value=value;
	}
	
	public ListNode(T value, ListNode nextNode) {
        this.value = value;
        this.next = nextNode;
    }

    public T getData() {
        return value;
    }

    public ListNode getNext() {
        return next;
    }

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

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

}

 

从尾到头打印链表

标签:目的   写法   pack   sys   rgs   从尾到头打印链表   his   turn   system   

原文地址:http://www.cnblogs.com/zhouym/p/6526768.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!