leetcode|简单:剑指 Offer 24. 反转链表

jupiter
2022-06-10 / 0 评论 / 583 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年06月10日,已超过679天没有更新,若内容或图片失效,请留言反馈。

1.题目

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

限制:

  • 0 <= 节点个数 <= 5000

2. 题解

2.1 思路分析

思路1:
    本题比较简单直接上代码

2.2 代码实现

  • 思路1
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null || head.next==null){
            return head;
        }

        ListNode newHead = head.next;
        ListNode nextNewHead = newHead.next;
        head.next = null;


        while (nextNewHead!=null){
            newHead.next = head;
            head = newHead;
            newHead = nextNewHead;
            nextNewHead = nextNewHead.next;
        }
        newHead.next = head;

        return newHead;
    }
}
  • 思路1优化
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

class Solution {
    public 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;
    }
}

2.3 提交结果

提交结果执行用时内存消耗语言提交时间备注
通过0 ms41 MBJava2022/06/10 11:15添加备注
提交结果执行用时内存消耗语言提交时间备注
通过0 ms40.8 MBJava2022/06/10 11:32添加备注

参考资料

  1. https://leetcode.cn/problems/fan-zhuan-lian-biao-lcof
0

评论 (0)

打卡
取消