天天看点

【List-easy】206. Reverse Linked List 反转链表

1. 题目原址

https://leetcode.com/problems/middle-of-the-linked-list/

2. 题目描述

【List-easy】206. Reverse Linked List 反转链表

3. 题目大意

给定一个链表,反转这个链表

4. 解题思路

  • 首先定义三个指针,当前指针cur, 当前指针的前一个指针 pre, 当前指针的后面的指针post
  • pre指向给定链表的头, cur指针给定链表的后一个元素,然后将给定链表的头指向null
  • 进入while循环,如果循环不为空,就进行反转 。最后返回pre

5. AC 代码

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode pre = head;
        ListNode cur = head.next;
        ListNode next;
        head.next = null;
        while(cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}
           

继续阅读