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();
}
}
逆序遍历链表--递归与非递归方法
关注
打赏