Middle-题目107:61. Rotate List

题目原文:
Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
题目大意:
把一个链表循环右移K位。
题目分析:
先把链表连成环(尾节点连到head上),并统计节点个数count,然后从head开始把第count-k%count个节点拆下来就行了。
源码:(language:c)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* rotateRight(struct ListNode* head, int k) {
    if(!head || !head->next)
        return head;
    struct ListNode* end;
    int count=1;
    for(end = head; end->next; end = end->next)
        count++;
    end->next = head;
    struct ListNode *p1=head,*p2=head->next;
    for(int i=1;i<count-k%count;i++) {
        p1=p1->next;
        p2=p2->next;
    }
    p1->next = NULL;
    return p2;
}

成绩:
4ms,beats 6.02%,众数4ms,93.98%
cmershen的碎碎念:
本题有一个陷阱在于,如果直接从环上找第k个点是错误的,因为这里的k可能远大于链表长度,而对环来说移动一圈相当于没动,所以取余即可。

你可能感兴趣的:(Middle-题目107:61. Rotate List)