leetcode-61 旋转链表

给定一个链表,旋转链表,将链表每个节点向右移动 个位置,其中 是非负数。

示例 1:

输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL

示例 2:

输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL

原理是先遍历整个链表获得链表长度n,然后此时把链表头和尾链接起来,在往后走n - k % n个节点就到达新链表的头结点前一个点,这时断开链表即可。

public ListNode rotateRight(ListNode head, int k) {
        if(head == null) return null;
        int n = 1;
        ListNode cur = head;
        while(cur.next != null){//统计链表的长度,到达链表的末尾
            n++;
            cur = cur.next;
        }
        cur.next = head;//将链表头与尾相连
        int m = n - k % n;
        for(int i = 0; i < m; i++){//往后走m步
            cur = cur.next;
        }
        ListNode newHead = cur.next;
        cur.next = null;//断开链表
        return newHead;
}

猜你喜欢

转载自blog.csdn.net/qq_43322057/article/details/84330333