Java实现链表反转算法

103 阅读1分钟

以下是一个使用Java实现反转链表的算法,包含链表节点定义和迭代反转方法:

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

public class ReverseLinkedList {
    // 迭代法反转链表
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;    // 前驱节点
        ListNode curr = head;    // 当前节点
        
        while (curr != null) {
            ListNode nextTemp = curr.next; // 临时保存下一个节点
            curr.next = prev;    // 反转指针方向
            prev = curr;         // 前驱节点后移
            curr = nextTemp;     // 当前节点后移
        }
        return prev; // 返回新链表头节点
    }
}

算法说明:

  1. 时间复杂度:O(n),遍历一次链表

  2. 空间复杂度:O(1),仅使用常量级额外空间

  3. 核心步骤

    • 使用三个指针:prev(前驱节点)、curr(当前节点)、nextTemp(临时存储)
    • 遍历链表,每次将当前节点的指针反向指向前驱节点
    • 移动指针直到链表尾部

使用示例:

public static void main(String[] args) {
    // 创建链表 1->2->3->4->5
    ListNode head = new ListNode(1);
    head.next = new ListNode(2);
    head.next.next = new ListNode(3);
    head.next.next.next = new ListNode(4);
    head.next.next.next.next = new ListNode(5);
    
    // 反转链表
    ReverseLinkedList reverser = new ReverseLinkedList();
    ListNode newHead = reverser.reverseList(head);
    
    // 输出:5->4->3->2->1
    while (newHead != null) {
        System.out.print(newHead.val + " ");
        newHead = newHead.next;
    }
}

递归解法(补充):

// 递归法反转链表
public ListNode reverseListRecursive(ListNode head) {
    if (head == null || head.next == null) {
        return head;
    }
    ListNode newHead = reverseListRecursive(head.next);
    head.next.next = head; // 反转指针
    head.next = null;      // 断开原指针
    return newHead;
}

提示:迭代法空间效率更优(O(1)),递归法代码更简洁但空间复杂度为O(n)。在实际应用中,迭代法是更推荐的做法。