Rotate ListNode In K Groups

来源:互联网 发布:运营数据分析报告范文 编辑:程序博客网 时间:2024/05/16 14:18

K个节点一组,反转链表;

public ListNode rotate(ListNode head, int k) {    if (head == null || head.next == null || k <= 1) {        return head;    }    ListNode dummy = new ListNode(-1);    dummy.next = head;    ListNode pre = dummy, cur = head;    int num = 0;    while (cur != null) {        num++;        cur = cur.next;    }    if (num >= k) {        cur = pre.next;        for (int i = 1; i < k; i++) {            ListNode next = cur.next;            cur.next = next.next;            next.next = pre.next;            pre.next = next;        }        pre = cur;        num -= k;    }    return dummy.next;}



原创粉丝点击