61. Rotate List

题目:

61. Rotate List

解答:

标记截断的位置,重新连接链表即可。

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(head == NULL || head->next == NULL)  return head;
        ListNode* p = head;
        int len = 0;
        while(p != NULL){
            p = p->next;
            ++len;
        }
        k = k % len;
        if(k == 0)  return head;
        p = head;
        while(k < len - 1){
            p = p->next;
            ++k;
        }
        ListNode *q = p->next;
        p->next = NULL;
        p = q;
        while(p->next != NULL)
            p = p->next;
        p->next = head;
        return q;
    }
};

更新会同步在我的网站更新(https://zergzerg.cn/notes/webnotes/leetcode/index.html)