题解 | #重排链表#

重排链表

https://www.nowcoder.com/practice/3d281dc0b3704347846a110bf561ef6b

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public void reorderList(ListNode head) {
        //特殊情况处理:(空节点,1个节点,2个节点) -> 这三种情况都不需要进行翻转
        if (head == null || head.next == null ||
                head.next.next == null) return;
        //找到中间位置的节点
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;// 此处一定要走2步,我多次写错
        }
        //反转slow之后的单链表
        ListNode cur = slow.next;
        ListNode curNext = cur.next;
        slow.next = null;
        while (cur != null) {
            curNext = cur.next;
            cur.next = slow;
            slow = cur;
            cur = curNext;
        }
        //此时slow就指向单链表的最后一个节点了
        ListNode nextHead = new ListNode(-1);
        ListNode nextSlow = new ListNode(
            -1);// 一开始不要赋值,否则3个节点的情况无法处理
        while (nextHead != nextSlow && nextSlow != null) {
            nextHead = head.next;
            nextSlow = slow.next;
            head.next = slow;
            if (nextSlow != null) {
                slow.next = nextHead;
                head = nextHead;
                slow = nextSlow;
            } else {
                slow.next = null;
            }
        }
    }
}

全部评论

相关推荐

喜欢吃蛋糕仰泳鲈鱼是我的神:字节可以找个hr 给你挂了,再放池子捞
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务