美文网首页
单链表反转

单链表反转

作者: HWilliamgo | 来源:发表于2018-06-03 21:21 被阅读6次
public class SingleLinkedList {
    private class Node {
        private Node next;
        private int value;
        Node(Node next, int value) {
            this.next = next;
            this.value = value;
        }
    }
    
    private Node head;
    private Node last;
    private int size;
    
    public SingleLinkedList() {
        Node firstNode = new Node(null, 0);
        head = firstNode;
        last = firstNode;
        size = 0;
    }

    public void add(int value) {
        Node node = new Node(null, value);
        last.next = node;
        last = node;
        size++;
    }

    public void clear() {
        size = 0;
        last = head;
    }
    //将链表倒进数组,再从数组逆序拿出,耗费更多内存。
    public void reverse() {
        int oldSize = size;
        Node cursor = head.next;
        Node[] nodes = new Node[oldSize];
        for (int i = 0; i < oldSize; i++) {//save all value to the nodes
            nodes[i] = cursor;
            cursor = cursor.next;
        }
        clear();//clear the linkedList
        for (int i = oldSize - 1; i >= 0; i--) {
            add(nodes[i].value);
        }
    }
    private void print(Node node) {
        if (node != null) {
            System.out.print(node.value + " ");
            print(node.next);
        }
    }
    public void print() {
        print(head.next);
    }
    //在原址上操作,通过递归从尾结点开始,将结点指针反转。
    private Node reverseHead(Node node) {
        if (node == null || node.next == null) {
            return node;
        }
        Node newHead = reverseHead(node.next);
        node.next.next = node;
        node.next = null;
        return newHead;
    }
    public void reverseHead() {
        last = head.next;
        head.next = reverseHead(head.next);
    }
}

reverseHead方法的图解:


image.png

剩下的画图跟着代码走一遍。

相关文章

  • Algorithm小白入门 -- 单链表

    单链表递归反转链表k个一组反转链表回文链表 1. 递归反转链表 单链表节点的结构如下: 1.1 递归反转整个单链表...

  • 单链表反转

    单链表 单链表反转 递归方法

  • Java、Python3 实战 LeetCode 高频面试之单链

    单链表反转 单链表反转这道题可谓是链表里面的高频问题了,差不多可以说只要被问到链表,就会问单链表反转。 今天我们就...

  • 链表简单算法相关练习

    单链表反转: 给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。 迭代方式实现: 复杂度分析: 时...

  • 5个链表的常见操作

    链表 链表反转 LeetCode206:给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。 环路检...

  • 反转链表

    给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

  • 【教3妹学算法】2道链表类题目

    题目1:反转链表 给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。 示例 1: 输入:head ...

  • js+链表

    链表结构 删除链表某节点 遍历 反转单链表

  • 反转单链表

    题目:反转单链表。

  • 单链表反转

    单链表反转 单链表初始化 输出 反转 释放 实现代码 尚未实现 元素插入 元素删除

网友评论

      本文标题:单链表反转

      本文链接:https://www.haomeiwen.com/subject/ytdssftx.html