61 Rotate List

按照题目思路,注意首先需要取余,保证K的大小合适

Python

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head:
            return head
        l = 1
        p = head
        while p.next:
            p = p.next
            l += 1
        k = k % l
        if k == 0:
            return head
        k = l - 1 - k % l 
        pp = head
        while k > 0:
            pp = pp.next
            k -= 1
        newHead = pp.next
        pp.next = None
        p.next = head
        return newHead

Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null){
            return head;
        }
        int l = 1;
        ListNode p = head;
        while(p.next != null){
            l += 1;
            p = p.next;
        }
        ListNode cur = head;
        k = k % l;
        if (k == 0){
            return head;
        }
        k = l - 1 - k % l;
        while(k > 0){
            cur = cur.next;
            k -= 1;
        }
        ListNode newHead = cur.next;
        cur.next = null;
        p.next = head;
        return newHead;
    }
}

results matching ""

    No results matching ""