[Leetcode] #61 Rotate List

来源:互联网 发布:淘宝的评论管理在哪里 编辑:程序博客网 时间:2024/06/07 06:38

Discription:

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.

Solution:

ListNode* rotateRight(ListNode* head, int k) {if (head == NULL) return NULL;int size = 0;ListNode *p1 = head, *p2 = head;while (p1){size++;p1 = p1->next;}k = k%size;p1 = head;for (int i = 0; i < k; i++){p2 = p2->next;}while (p2->next){p1 = p1->next;p2 = p2->next;}p2->next = head;head = p1->next;p1->next = NULL;return head;}
ListNode* rotateRight(ListNode* head, int k) {if (!head) return head;int len = 1; // number of nodesListNode *newH, *tail;newH = tail = head;while (tail->next)  // get the number of nodes in the list{tail = tail->next;len++;}tail->next = head; // circle the linkif (k %= len){for (auto i = 0; i<len - k; i++) tail = tail->next; // the tail node is the (len-k)-th node (1st node is head)}newH = tail->next;tail->next = NULL;return newH;}

附:Leetcode源代码见我的GitHub 

0 0
原创粉丝点击