206. 反转链表

63 阅读1分钟

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。力扣题目

 

示例 1:

输入: head = [1,2,3,4,5]
输出: [5,4,3,2,1]

示例 2:

输入: head = [1,2]
输出: [2,1]

示例 3:

输入: head = []
输出: []

 

提示:

  • 链表中节点的数目范围是 [0, 5000]
  • -5000 <= Node.val <= 5000

 

进阶: 链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题? 解题思路: 1、创建新链表 2、双指针写法 3、递归写法

创建新链表接收

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode cur = head;
        //这个节点来做为新链表的头,
        ListNode pre = null;
        while (cur != null) {
            //临时存放cur下一个节点
            ListNode tmp = cur.next;
            //新遍历到的节点指向pre节点
            cur.next =pre;
            //pre指针移动到cur,作为新链表的头
            pre= cur;
            //老的链表往后遍历
            //cur = cur.next;//这个时候cur.next已经在新链表了,不能再用了
            cur =tmp;
        }
        return pre;
    }
}

双指针写法

/**
 * 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) {
        //双指针写法
        ListNode cur = head;
        ListNode prev  =null;
        ListNode temp  =null;
        while (cur!=null) {
            temp = cur.next;
            cur.next =prev;
            prev =cur;
            cur =temp;
        }
        return prev;
    }
}

递归写法(往前递归)

/**
 * 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) {
        //双指针写法
        ListNode cur = head;
        ListNode prev  =null;
        ListNode temp  =null;
        while (cur!=null) {
            temp = cur.next;
            cur.next =prev;
            prev =cur;
            cur =temp;
        }
        return prev;
    }
    private ListNode reverse(ListNode prev,ListNode cur){
        if(prev == null){
            return prev;
        }
        ListNode temp = cur.next;
        cur.next = prev;
        prev = cur;
       return reverse(prev, temp);
    }
}