LeetCode 精选 TOP 面试题(Java 实现)—— 反转链表

一、题目描述

1.1 题目
  • 反转链表

  • 反转一个单链表。

  • 示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
  • 进阶:
    你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
1.2 知识点
  • 链表
1.3 题目链接

二、解题思路

2.1 自研思路

  两种思路:

  • Java JDK 中经常使用的头插法(HashMap);
  • 递归法,直接尾递归即可,每次递归的参数为前节点和当前节点;

三、实现代码

3.1 迭代实现(头插法)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        
        ListNode retHead = new ListNode(-1);
        ListNode ptr = head;

        while(ptr != null){
            ListNode node = ptr;
            ptr = ptr.next;
            node.next = retHead.next;
            retHead.next = node;
        }

        return retHead.next;
    }
}
3.2 递归法(尾递归)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        return reverseList(null, head);
    }

    private ListNode reverseList(ListNode pre, ListNode cur) {
        if(cur == null) return pre;
        ListNode next = cur.next;
        cur.next = pre;
        return reverseList(cur, next);
    }
}
发布了277 篇原创文章 · 获赞 33 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_40697071/article/details/104047756