【题目】

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

把链表12345反转成54321

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

 

Example 1:

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

Example 2:

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

Example 3:

Input: head = []
Output: []

 

 

【思路】

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

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

 

Q:还要想清楚问什么是while(cur!=null) ,以及为什么最后返回的是pre

A:因为cur是第一个需要用到的(cur.next),pre经过一系列操作到了头部

 

【代码】

    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;
    }

 

 posted on 2021-08-31 16:51  alau  阅读(19)  评论(0编辑  收藏  举报