【leetcode】206. 反转链表

题目:206. 反转链表 - 力扣(LeetCode) (leetcode-cn.com)

思路1:

迭代

对链表迭代,遍历到每一个元素,让该元素指针前一个节点;

这里需要注意的是要注意保存前驱节点以及后驱节点;

 

代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
       // 迭代
       // 遍历链表,讲节点指向前一个节点
      
       // 第一个节点的前驱是null
       ListNode prev = null;
       //指向当前节点
       ListNode curr = head;
       while(curr != null){
           ListNode next = curr.next;
           curr.next = prev;
           prev  = curr;
           curr = next;
       }

       return prev;
    }
}

 

 

 

思路2:

递归

分析发现有相似的算法逻辑,都是通过将剩下的元素的反转,进而可以得到整个链表的反转

递归base case:

当链表为空的时候,不用反转了直接返回空

当链表为一个元素,反转后即为本身

故base case: 

if(head == null|| head.next == null) return head;

代码如下:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
       // 递归base case
       if(head == null || head.next == null) return head;
       // 递归: last得到的是一个不包含head的反转链表
       // 递归思想: 有相似的逻辑
       ListNode last = reverseList(head.next);
       head.next.next = head;
       head.next = null;
       return last;
    }
}

 

posted @ 2022-05-01 20:10  MintMin  阅读(14)  评论(0编辑  收藏  举报