算法题:反转链表

87 阅读1分钟
// 定义链表节点类
public class ListNode {  
    int val;  // 节点存储的数据
    ListNode next;  // 指向下一个节点的指针

    // 构造函数,初始化节点值
    ListNode(int x) { 
        val = x; 
    }  
}  


// 定义反转链表类
class Solution {
    // 反转以 head 为起点的但链表
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        // 由于单链表的结构,至少要用三个指针才能完成迭代反转
        // cur 是当前遍历的节点,pre 是 cur 的前驱结点,nxt 是 cur 的后继结点
        ListNode pre, cur, nxt;
        pre = null; cur = head; nxt = head.next;
        while (cur != null) {
            // 逐个结点反转
            cur.next = pre;
            // 更新指针位置
            pre = cur;
            cur = nxt;
            if (nxt != null) {
                nxt = nxt.next;
            }
        }
        // 返回反转后的头结点
        return pre;
    }
}

这段代码通过迭代的方式反转了一个单链表。 它使用了三个指针:prev(前一个节点),curr(当前节点),和nextTemp(临时保存当前节点的下一个节点)。 在每次迭代中,它都会将curr.next指向prev,然后更新prevcurr的值,以便在下一次迭代中处理下一个节点。 最终,prev将指向反转后链表的头部,并作为方法的结果返回。