链表之倒序打印(Java)

思路:

1、压入栈中打印

2、递归打印

注意:不建议反转链表后打印,会破坏链表结构

package com.datastructure.link;

import java.util.Stack;

/*
 * 数据结构之倒序打印单链表
 */
public class ReversePrintLinkedList
{

    /*
     * 元素的基本定义
     */
    static class Node{
        /*
         * value
         */
        private int value;
        
        /*
         * 链表的下一个元素
         */
        private Node next;
        
        public Node (int value) {
            this.value = value;
        }
        
        @Override
        public String toString() {
            if (this.next == null) {
                return String.valueOf(this.value);
            }
            return this.value + "->" + this.next.toString();
        }
        
    }
    
    /*
     * 倒序打印单链表
     * 
     * 思路:遍历链表,把元素压入栈中,利用栈后进先出特性,遍历栈中元素,逐个打印
     * 
     * 分析:不要使用链表反转后打印,会破坏
     */
    public static void reversePrint(Node node) {
        if (node == null) {
        	throw new RuntimeException("node is empty");
        }
    	
    	Stack<Node> stack = new Stack<>();
    	while (node != null) {
    		stack.push(node);
    		node = node.next;
    	}
    	
    	System.out.print("Reverse link values: ");
    	while (!stack.empty()) {
    		System.out.print(stack.pop().value + " ");
    	}
    	
    }

    public static void reversePrintLink(Node node) {
    	if (node == null) {
    		return;
    	}
        reversePrintLink(node.next);
    	System.out.print(node.value + " ");
    }
    
    
    public static void main(String args[]) {
        
        Node head = createTestLinkedList();
        // 原链表
        System.out.println("Origin link: " + head);
        
        // 倒序打印链表
        reversePrint(head);
        
        
        System.out.print("\nReverse link values: ");
        reversePrintLink(head);
    }
    
    private static Node createTestLinkedList() {
        Node head = new Node(0);
        Node curNode = head;
        for (int i = 1; i < 10; i++) {
            curNode.next = new Node(i);
            curNode = curNode.next;
        }
        return head;
    }

}

猜你喜欢

转载自blog.csdn.net/zangdaiyang1991/article/details/88580322
今日推荐