JZ-015-反转链表

反转链表
题目描述

输入一个链表,反转链表后,输出新链表的表头。

题目链接: 反转链表

代码
/**
 * 标题:反转链表
 * 题目描述
 * 输入一个链表,反转链表后,输出新链表的表头。
 * 题目链接:
 * https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&&tqId=11168&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
 */
public class Jz15 {

    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode first = head, second = head.next;
        first.next = null;
        while (first != null && second != null) {
            ListNode temp = first;
            first = second;
            second = second.next;
            first.next = temp;
        }
        return first;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        System.out.println("before reverse");
        ListNode cur = head;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
        Jz15 jz15 = new Jz15();
        ListNode result = jz15.reverseList(head);
        System.out.println("after reverse");
        ListNode cur1 = result;
        while (cur1 != null) {
            System.out.print(cur1.val + " ");
            cur1 = cur1.next;
        }
    }
}

【每日寄语】 生活的本质就是幸福的活着,而生活的智慧就是活出自己想要的样子。

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

醉舞经阁-半卷书

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值