Listcode 61

只要记录倒数第二个结点和倒数第一个节点,倒数第二个结点指向NULL,倒数第一个结点指向头结点,循环k次变得到结果,注意开始前应处理k,使其取除以size的余数,否则会time limited exceed

struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
 };
ListNode* rotateRight(ListNode* head, int k) {
        if(head==NULL||head->next==NULL)return head;
        int count = 0;
        ListNode* p=head;
        while(p){
            count++;
            p=p->next;
        }
        k%=count;
        for(int i=0;i<k;i++)
        {
            ListNode* p=head;
            while(p->next->next!=NULL)p=p->next;
            ListNode* q = p->next;
            p->next = NULL;
            q->next=head;
            head=q;
        }
        return head;
    }

猜你喜欢

转载自blog.csdn.net/TempterCyn/article/details/83833738
61
61-
61A
T61