Fork me on GitHub

【数据结构】算法 Rotate List 旋转链表

Rotate List 旋转链表

Given the head of a linked list, rotate the list to the right by k places.

Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL

首尾相连,旋转断开

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head==null){
            return null;
        }
        int n = 1;
        ListNode p = head;//p指向head
        while (p.next!=null){
            p = p.next;
            n++;
        }//n 表长度

        p.next = head;
        k%=n;
        k = n-k;//p从head向后移动n-k
        while (k>0){
            k--;
            p=p.next;
        }
        head =p.next;
        p.next =null;
        return head;
    }
}
posted @ 2021-03-10 11:33  WilliamCui  阅读(83)  评论(0编辑  收藏  举报