头插法创建&原地逆置单链表 【Java】

本文介绍了一种使用头插法创建单链表的方法,并实现了单链表的原地逆置。通过示例代码展示了如何创建一个逆序存储元素的链表及逆置后的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、头插法创建&原地逆置单链表

public class RotateList {

    public static void main(String[] args) {
        int [] values = new int[]{1,2,3,4};
        Node head = constructList(values);
        printResult("链表创建后结构: ", head);
        Node newHead = reverseList(head);
        printResult("链表逆置后结构: ", newHead);
    }

    /***
     * 头插法创建链表
     * @param values
     * @return
     */
    public static Node constructList(int [] values){
        Node head = new Node(values[0], null);
        for(int i = 1; i <= values.length -1; i++){
            Node node = new Node(values[i], null);
            node.next = head.next;
            head.next = node;
        }
        return head;
    }

    /***
     * 逆置链表
     * @param head
     * @return
     */
    public static Node reverseList(Node head){
        Node pre = null;
        Node cur = head;
        Node next = cur.next;
        while(next != null){
            cur.next = pre;
            pre = cur;
            cur = next;
            next = cur.next;
        }
        cur.next = pre;
        return cur;
    }

    /***
     * 打印结果
     * @param comment
     * @param head
     */
    public static void printResult(String comment, Node head){
        System.out.print(comment);
        Node cur = head;
        while(cur != null){
            System.out.print(cur.value + "-->");
            cur = cur.next;
        }
        if(cur == null){
            System.out.print("null");
        }
        System.out.println();
    }
}

二、运行结果

链表创建后结构: 1-->4-->3-->2-->null
链表逆置后结构: 2-->3-->4-->1-->null
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值