3月打卡活动第2天 LeetCode第206题:反转链表(简单)

3月打卡活动第2天LeetCode第206题:反转链表(简单)

  • 题目:反转一个单链表。
    在这里插入图片描述
  • 解题思路1:想起了第25题,思路一样的。
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null) return head;

        ListNode startNode = head,stopNode = head;
        while(stopNode.next!=null){
            stopNode = stopNode.next;
        }
        stopNode = reverse(startNode,stopNode);

        return stopNode;
    }

    ListNode reverse(ListNode startNode, ListNode stopNode){    //链表反转
        ListNode pre = null, cur = startNode, stop = stopNode.next;
        while(cur!=stop){
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }

        return pre;
    }

}

在这里插入图片描述

  • 解题思路2:题中要求用迭代或递归,我又试了试。从后往前依次取,我这叫迭代不。。。
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null) return head;
        int count=0;
        ListNode stopNode = head;
        while(stopNode.next!=null){
            stopNode = stopNode.next;
            count++;
        }
        ListNode startNode = stopNode;
        while(count>0){
            stopNode.next=reverse(head,--count);
            stopNode=stopNode.next;
        }
        return startNode;
    }

    ListNode reverse(ListNode startNode,int count){  
        ListNode  pre = null,cur = startNode;
        while(count>0){
            cur = cur.next;
            count--;
        }
        cur.next=pre;
        return cur;
    }

}

在这里插入图片描述

  • 题解做法:这才是真正的递归,从最后一个往前推。
public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) return head;
    ListNode p = reverseList(head.next);
    //相当于加上了 5 -> 4,存在一个闭环 
    head.next.next = head;
    //切断之前的联系
    head.next = null;
    return p;
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/reverse-linked-list/solution/fan-zhuan-lian-biao-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

在这里插入图片描述

发布了100 篇原创文章 · 获赞 12 · 访问量 2366

猜你喜欢

转载自blog.csdn.net/new_whiter/article/details/104606283
今日推荐