单链表反转-IDE完整代码

这篇博客主要介绍了如何为面试准备手撕代码,重点聚焦于单链表的反转操作。通过定义结点类并提供完整的代码实现,详细阐述了单链表反转的过程。

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

为了面试中手撕代码,练习单链表的初始化

结点类的定义如下:

public class ListNode {
    int val;
    ListNode next;

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

完整代码如下:

public class Solution {
    public static void main(String[] args) {
        ListNode fourth=new ListNode(4,null);
        ListNode third=new ListNode(3,fourth);
        ListNode second=new ListNode(2,third);
        ListNode first=new ListNode(1,second);  //创建链表

        System.out.println("反转之前的链表:");
        print(first);
        reverseList(first);
        System.out.println("反转之后的链表:");
        print(fourth);
    }

    //实现单链表的打印
    public static void print(ListNode head){
        ListNode temp=head;
        while(temp!=null){
            System.out.print(temp.val+" ");
            System.out.println();
            temp=temp.next;
        }
    }
	//反转链表
    public static ListNode reverseList(ListNode head) {
        //双指针
        ListNode pre=null,cur=head;
        while(cur!=null){
            ListNode tmp=cur.next;
            cur.next=pre;
            pre=cur;
            cur=tmp;
        }
        return pre;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值