Rotate List--LeetCode
来源:互联网 发布:驱鼠器 知乎 编辑:程序博客网 时间:2024/06/16 04:51
题目:
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
- [leetcode][list] Rotate List
- LeetCode: Rotate List
- LeetCode Rotate List
- LeetCode : Rotate List
- [Leetcode] Rotate List
- [LeetCode] Rotate List
- [leetcode] Rotate List
- leetcode 70: Rotate List
- [Leetcode] Rotate List
- 【leetcode】Rotate List
- [LeetCode]Rotate List
- [leetcode]Rotate List
- LeetCode-Rotate List
- [leetcode] Rotate List
- LeetCode - Rotate List
- LeetCode:Rotate List
- LeetCode 61: Rotate List
- leetcode之Rotate List
- 从一个简单程序的GDB调试看段错误,指针的初始化及内存分配(malloc/free)
- Java 类加载机制
- Java多线程和高并发
- 模板处理数组
- HDU5200
- Rotate List--LeetCode
- [LeetCode]Largest Number, 解题报告
- 数值分析2.2 直接三角分解方法
- Java 反射机制
- Input标签中Type的类型及用法
- PAT(BASIC)1015. 德才论 (25)
- vb.net操作数据库之ACCESS(一)
- TeX文档的基本结构
- F5 F5+Ctrl 浏览器地址 Enter