反向打印单链表

package com.study;

/**
 * 从尾到头打印单链表
 * */
class Node {
    public int data;
    public Node next;
    public Node() {
        
    }
}

class Stack {
    
    private static final int MAXSIZE = 10;
    
    private static int point = 0; //指向栈顶
        
    
    private static int[] arr = new int[MAXSIZE];
    
    public static void push(int data) {
        if(point < MAXSIZE) {
            arr[point] = data;
            point++;
        }
        else {
            System.out.println("The stack is full");
        }
    }
    
    public static int pop() {
        if( point > 0) {
            point--;
            return arr[point];
        }
        else {
            return -1;
        }
    }
}

public class suanfa3 {
    
    private static int[] arr = {1,2,3,4,5};

    /*根据数组创建单链表*/
    public static void CreateList(int[] arr, Node head) {
        if(head != null) {
            for(int i = 0; i < arr.length; i++) {
                Node node = new Node();
                node.data = arr[i];
                node.next = head.next;
                head.next = node;
            }   
            
        }
    }
    
    /*顺序打印单链表*/
    public static void PrintList(Node head) {
        Node pNode;//游标
        if(head != null) {
            while(head.next != null) {
                pNode = head.next;
                System.out.print(pNode.data+"-->");
                head =  head.next;
            }
            System.out.println("NULL");
        }
    }
    
    /*不改变原来的链表结构打印,可以考虑以空间换取时间来提高效率**/
    public static void ReversePrintWithoutChange(Node head) {
        
        int data;
        /*入栈**/
        while(head.next != null) {
            Stack.push(head.next.data);
            head = head.next;
        }
        
        /*出栈*/
        
        while((data = Stack.pop()) != -1) {
            System.out.print(data + "-->");
        }
        
        System.out.println("NULL");
    }
    
    public static void main(String[] args) {
        Node node = new Node();
        CreateList(arr,node);
        PrintList(node);
        ReversePrintWithoutChange(node);
    }
    
}

因为是单链表,所以无法遍历到尾节点,然后在倒回去打印。这里有两种解决思路:

1.不改变该链表结构的情况下,由于先遍历到的节点后打印,所以符合栈的特点,所以自然想到可以建立一个栈存储先遍历到的节点。然后再出栈即可。如上面的代码所示。

2.先逆转单链表,然后再顺次遍历,但是这样会改变原来的链表结构。关于逆转单链表,请参考本博客的其他文章。

转载于:https://www.cnblogs.com/xuehanlee/p/4613395.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值