栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java手写单链表的反转

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java手写单链表的反转

代码实现
public class SingleNodeTest {
    private static class Node{
        private int value;
        private Node next;

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

        public Node(int value,Node node) {
            this.value = value;
            this.next = node;
        }
    }

    public Node reverseList(Node head){
        if(head == null){
            return null;
        }
        Node prev = head;
        Node current = head.next;
        prev.next = null;
        while (current != null){
            Node next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        return prev;
    }

    public static void main(String[] args) {
        Node node = new Node(1,new Node(2,new Node(3,new Node(4,new Node(5,null)))));
        SingleNodeTest singleNodeTest = new SingleNodeTest();
        Node listNode = singleNodeTest.reverseList(node);
        System.out.println();
    }
}

测试结果:原链表 1->2->3->4->5,结果 5->4->3->2->1

思路讲解

单向链表反转的思想就是next指针重新指向前一个节点,所以需要定义变量把前一个节点引用保存下来。通过挪动prev和current节点位置,再把next重新指向实现单链表的反转。

进入reveraeList方法,prev节点等于head节点也就是等于1,current节点等于head节点的next节点也就是等于2,prev节点的next的指向等于null,就是把1指向2的next指向移除掉。进入while第一次循环,next等于current节点的next节点也就是3保存下来,current节点的next从指向3改成指向1,然后移动prev和current节点,prev节点从原来1移动到2,current节点从原来的2移动到3。同时删除2指向3的next引用,因为反转之后2的next指向1。然后进入下次循环。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1031496.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号