Rotate List--LeetCode

来源:互联网 发布:驱鼠器 知乎 编辑:程序博客网 时间:2024/06/16 01:08

题目:

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个节点 也就是将后面的k个节点移动到最前面 void RotateList(List*& list,int k){if(list == NULL || list->next == NULL || k<=0)return ;int length=1;List* head = list;List* tmp; while(head != NULL){head = head->next;length++;} int last = k%length; //最后的Last个节点移动到最前方 int pre =1;head = list;while(pre <(length-last)-1){head = head->next;pre++;} cout<<"head is " <<head->value<<endl;List* new_head= head->next;tmp = head->next;head->next = NULL;while(tmp != NULL && tmp->next != NULL){tmp = tmp->next;} tmp->next = list;list = new_head;} 

ps:用两个指针,一快一慢,使得中间间隔为K,然后,遍历到最后,将这段链表直接和链表的头部连接即可。

0 0
原创粉丝点击