【001】如何实现一个高效的单向链表逆序输出(Java版)

2019-06-19  本文已影响0人  山枫叶纷飞

如题

01. 先学着实现一个简单的Java版的单项链表

构建任意长度的任意数值的链表, 头插法,顺序遍历输出链表

package com.szs.list;
/**
 * 单链表
 * @author Administrator
 *
 */
public class MyLinkedList {
    public int data;
    public MyLinkedList next;
    
    public MyLinkedList(int data) {
        this.data=data;
        this.next=null;
    }
    public MyLinkedList() {
        this.data=-1;
        this.next=null;
    }
}

02.编写上面的单项链表的逆序输出

高效的输出链表,直接使用栈来存储~~

package com.szs.list;

import java.util.Random;
import java.util.Stack;

public class InverseSingleList {
    
    public static void main(String[] args) {
        MyLinkedList head=  new MyLinkedList();
        createList(head);
        inverseList(head);
    }
    /**
     * 构建任意长度的任意数值的链表, 头插法
     */
    public static void createList(MyLinkedList head) {
        Random random = new Random(System.currentTimeMillis());
        int len = random.nextInt(10);
        for(int i=0;i<len;i++) {
            int data = random.nextInt(100);
            MyLinkedList next =  new MyLinkedList(data);
            next.next = head.next;
            head.next = next;
        }
        /**
         * 顺序遍历输出链表
         */
        MyLinkedList head2 = head.next;
        System.out.println("顺序");
        while(head2!=null) {
            System.out.print(head2.data+"\t");
            head2=head2.next;
        }
        System.out.println("length="+len);
    }
    /**
     * 高效的输出链表,使用栈来存储
     */
    public static void inverseList(MyLinkedList head) {
        MyLinkedList head2 = head.next;
        Stack<Integer> stack = new Stack<>();
        System.out.println("逆序");
        while(head2!=null) {
            stack.push(head2.data);
            head2=head2.next;
        }
        while(!stack.isEmpty()) {
            System.out.print(stack.pop()+"\t");
        }
        
    }
}

03.进行测试

顺序
25  69  10  28  23  89  32  2   23  length=9
逆序
23  2   32  89  23  28  10  69  25  
-------
顺序
28  35  83  99  88  length=5
逆序
88  99  83  35  28  
上一篇 下一篇

猜你喜欢

热点阅读