(二十四) 单链表的逆置(java)

前言:单链表的逆置总是看完博客,当时懂了过一段时间就忘了,还是动手写一下加深一下印象吧。


参考博客:点击打开链接


demo地址:我的github


1. 单链表

先写一个简单的单链表,改写一下它的toString方法,打印出以该Node为head的单链表,方便调试。
package com.example.demo_24_chain_reversed;

public class Node {
    public int value;
    public Node nextNode;
    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value + "-->" + (nextNode != null ? nextNode.toString() : "null");
    }
}

2.单链表的递归逆置

先看下效果:

(二十四) 单链表的逆置(java)_第1张图片

用专业的话来说就是:递归方法用的是栈的思想,先把头结点入栈,接着头结点的下一个结点入栈,直到尾结点位置,

接着依次把栈内的元素出栈,并更换其下一个结点对应的对象:


我个人理解就是一个单链表的逆置总是可以分解成一个head和它nextNode的逆置,只要head的nextNode逆置好了,然后再添上head就好了,这就用到了递归。上面我打印出的log也可以看出来。


3. 单链表的非递归逆置

非递归的方法其实就是顺着头结点往尾结点便利,遍历期间把每个结点的nextNode替换掉,
替换过程需要注意临时存储下一个节点

(二十四) 单链表的逆置(java)_第2张图片


4.demo源码

package com.example.demo_24_chain_reversed;

public class MyClass {
    public static void main(String[] args){
        Node a = new Node(1);
        Node b = new Node(2);
        Node c = new Node(3);
        Node d = new Node(4);
        a.nextNode = b;
        b.nextNode = c;
        c.nextNode = d;
        //reverseChainRecursive(a);
        reverseChainNotRecursive(a);
    }

    private static Node reverseChainRecursive(Node head){
        System.out.println("before "+ head);
        if(head == null || head.nextNode == null){
            System.out.println("after " + head);
            return head;
        }
        Node headOfReverseChain = reverseChainRecursive(head.nextNode);
        head.nextNode.nextNode = head;
        head.nextNode = null;
        System.out.println("after "+ headOfReverseChain);
        return headOfReverseChain;
    }

    private static Node reverseChainNotRecursive(Node head) {
        Node pre = head;
        Node cur = head.nextNode;
        Node tmp;
        // 头结点的nextNode应该要置空
        pre.nextNode = null;
        while (cur != null) {
            // 先存放nex结点
            tmp = cur.nextNode;
            // 修改next结点指向pre
            cur.nextNode = pre;
            System.out.println("not ready "+ tmp);
            System.out.println("already "+ cur);
            System.out.println("---------");
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
}


你可能感兴趣的:(Android)