Loading

剑指 Offer 24. 反转链表

剑指 Offer 24. 反转链表

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

示例:

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

限制:

0 <= 节点个数 <= 5000

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
      //定义pre,这是一个中转站
        ListNode pre = null;
      //cur是指向头节点,保证cur不能为空
        ListNode cur = head;
        while(cur != null){
          //cur不为空时,创建tmp为cur的下一个节点
            ListNode tmp = cur.next;
          //cur下一个节点指向pre,此时是 pre(null) <-- cur
            cur.next = pre;
          //此时 Null <-- pre/cur -->tmp
            pre = cur;
          //    Null <-- pre --> tmp/cur 
            cur = tmp;
          //那么下一轮继续这种操作,反转链表
        }
        return pre;
    }
}
posted @ 2021-09-22 11:21  Pen9  阅读(24)  评论(0)    收藏  举报