Rotate List
来源:互联网 发布:李荣浩后羿知乎 编辑:程序博客网 时间:2024/04/30 19:50
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等于0及k大于链表长度的情况,可以通过取余就可以解决,对于这个题目,我们可以设置两个指针,一前一后,前面的指针走到第k个节点,后面指针走到第一个节点,知道前面的指针走到链表末尾,那么后面指针就是第K个节点,然后进行旋转。
class Solution {public: ListNode* rotateRight(ListNode* head, int k) { ListNode *pHead, *pAhead,*pBehind,*temp,*p,*p1; int n = 1; int count = 0; if(head == NULL) //考虑空节点 { return NULL; } pHead = head; pAhead = head; temp = head;while(temp) //获取链表长度 { count++; temp = temp->next; } k = k % count; if(k==0||head->next == NULL) //考虑k =0 { return head; } while(n < k) //前一个指针,指向第k个节点 { pAhead = pAhead->next; n++; } pBehind = head; while(pAhead->next) { p = pAhead; pAhead = pAhead->next; p1 = pBehind; pBehind = pBehind->next; } if(k == 1) //考虑仅末尾节点进行旋转 { p->next= NULL; pAhead->next = head; return pAhead; } pAhead->next = head; //非末尾节点旋转。 pHead =p1->next; p1->next = NULL; return pHead; }};
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
- Path Sum II ---LeetCode
- 员工没热情?这8个简单方法比加薪都管用
- spring 之 PropertiesLoaderUtils 获取文件属性用法
- 深度学习的40种应用
- Codeforce 382总结
- Rotate List
- 流氓鲁大师劫持了我的谷歌浏览器
- 汇编中16进制装换成为其他进制(2,8,10)
- 单例设计模式
- (一)RocketMQ初步认知
- TCP_NODELAY 和 TCP_NOPUSH
- ckeditor 上传图片 关键过程和代码
- Java内存空间,基本数据类型,数组
- nginx源代码分析 - 启动(七) IO多路复用模型的使用