61. Rotate List

来源:互联网 发布:通达信的软件 编辑:程序博客网 时间:2024/06/07 06:55

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.

分析:
先令一个指针node跑到最后的一个节点(非NULL)处;
让node的下一个指针指向头结点形成环形单链表;
然后就是计算要遍历的次数。这里分为三种情况:
1.k>n: k=k%n>0;
2.k

/** * 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) return NULL;        ListNode* node=head;        int n=1;//这里必须为1,否则后面k=k%n的时候不对        while(node->next){            node=node->next;            n++;        }        node->next=head;        if(k %= n)        {            int n1=n-k;//循环次数            while(n1--!=0) node=node->next;        }        ListNode* newhead=head;        newhead=node->next;        node->next=NULL;        return newhead;    }};