Rotate List
来源:互联网 发布:js如何获取select的值 编辑:程序博客网 时间:2024/06/06 01:22
原题:
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为0时原串返回,k>0时对链表的长度取余,然后把链表分成前后两个部分,然后重置链表头和尾的指针即可。可以AC的C++代码如下:
ListNode* rotateRight(ListNode* head, int k) { if(!head || !head->next) return head; if(k<0) return NULL; int length = 0; ListNode *pHead = head; while(pHead){ length ++; pHead = pHead->next; } int rotate = length - k % length; pHead = head; ListNode *tail = NULL, *newHead = head; for(int i=0; i< rotate; i++){ if(i == (rotate -1)){ tail = pHead->next; pHead->next = NULL; break; }else pHead = pHead->next; } if(tail) newHead = tail; while(tail && tail->next){ tail = tail->next; } if(tail) tail->next = head; return newHead; }
0 0
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- rotate-list
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- STL:使用模板计算一组整形数的最小值
- KMeans聚类算法思想与可视化
- jquery选择器大全
- iOS应用本地化-文本信息本地化
- LeetCode(88)Merge Sorted Array
- Rotate List
- Traits
- hdoj2066一个人的旅行
- PageRank
- 混合背包 hdu5410 CRB and His Birthday
- 遍历图像的方法及速度
- Sencha Touch CRUD
- 尾号限行api,单双号限行查询数据库接口调用代码示例
- 使用PowerDesigner创建mysql数据库表