【题目】

反转链表是之后很多题的基础

把链表12345反转成54321

Given the head of a singly linked list, reverse the list, and return the reversed list.

 

Example 1:

[Leetcode 206]反转链表Reverse Linked List_反转链表

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:

[Leetcode 206]反转链表Reverse Linked List_Easy_02

Input: head = [1,2]
Output: [2,1]

Example 3:

Input: head = []
Output: []

 

 

【思路】

最直观的是用stack,先进后出的特性,但这样需要额外的O(N)空间

为节省空间,对链表本身进行处理,核心思想是把每个节点的next指向前一个节点

[Leetcode 206]反转链表Reverse Linked List_链表_03

 

 

 

【代码】

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