zoukankan      html  css  js  c++  java
  • 反向打印单链表

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

  • 相关阅读:
    【原创】禁止快播自动升级到最新版本,自己发现的方法
    又一灵异事件 Delphi 2007 在 Win7
    [DCC Error] E2161 Error: RLINK32: Error opening file "_____.drf"
    单例模式 改进
    estackoverflow with message 'stack overflow'
    所有可选的快捷键列表[转自万一博客]
    SQL server 除法运算
    正则表达式的一个坑[.\n]无效引起的血案
    getcwd()和__DIR__区别
    并发处理的技巧php
  • 原文地址:https://www.cnblogs.com/xuehanlee/p/4613395.html
Copyright © 2011-2022 走看看