leetcode 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.



class Solution {
 public:
	 ListNode* rotateRight(ListNode* head, int k) {
		 if (k == 0)
			 return head;
		 ListNode*p = head;
		 int len = 0;
		 while (p != NULL)
		 {
			 p = p->next;
			 len++;
		 }
		 if (len == 0||len==1)
			 return head;
		 k = k%len;
		 if (k == 0)
			 return head;
		 p = head; int kk = 1;
		 while (kk != len - k)
		 {
			 p = p->next;
			 kk++;
		 }
		 ListNode*p1 = p->next, *p2 = p->next;
		 while (p1->next != NULL)
			 p1 = p1->next;
		 p1->next = head;
		 p->next = NULL;
		 head = p2;
		 return head;
	 }
 };

accepted


你可能感兴趣的:(LeetCode)