您当前的位置: 首页 >  链表
  • 0浏览

    0关注

    674博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

逆序遍历链表--递归与非递归方法

沙漠一只雕得儿得儿 发布时间:2016-11-15 10:58:42 ,浏览量:0

package 链表上;

import java.util.Stack;
/**
 * 初始化链表节点
 * @author buder_cp
 *
 * @param 
 */
class ListNode {
	public T value;
	public ListNode next;
	
	public ListNode(){}
	
	public ListNode(T value, ListNode next) {
		super();
		this.value = value;
		this.next = next;
	}
	
	public ListNode pre;
}

public class MiniList {
	private ListNode head = new ListNode(null, null);

	/**
	 * 数组转化成链表
	 */
	public void arrayToList(T[] array) {
		ListNode p = head;
		for (T t : array) {
			ListNode node = new ListNode(t, null);
			p.next = node;
			p = node;
		}
	}

	/**
	 * 打印链表
	 */
	public void printList() {
		ListNode p = head.next;
		while (p != null) {
			System.out.print(p.value + " ");
			p = p.next;
		}
		System.out.println();
	}


	/**
	 * 逆序打印单向链表,非递归,利用栈
	 * 
	 * @param args
	 */
	public void printInverse() {
		Stack stack = new Stack();
		ListNode p = head.next;
		while (p != null) {
			stack.push(p.value);
			p = p.next;
		}
		while (!stack.isEmpty()) {
			System.out.print(stack.pop() + " ");
		}
		System.out.println();
	}

	/**
	 * 逆序打印单向链表,递归法
	 * 
	 * @param args
	 */
	public void printInverseRecursive() {
		recursive(head.next);
		System.out.println();
	}

	private void recursive(ListNode p) {
		// TODO Auto-generated method stub
		if (p != null) {
			recursive(p.next);
			System.out.println(p.value + " ");
		}
	}

	public static void main(String[] args) {
		MiniList list = new MiniList();
		Integer[] array = { 1, 2, 3, 4, 5, 6 };
		list.arrayToList(array);
		System.out.print("original: ");
		list.printList();

		System.out.print("Inverse print: ");
		list.printInverse();
	}
}
关注
打赏
1657159701
查看更多评论
立即登录/注册

微信扫码登录

0.0371s