lintcode:Rotate List
来源:互联网 发布:mac电脑安装双系统 编辑:程序博客网 时间:2024/06/15 15:27
Given a list, rotate the list to the right by k places, where k is non-negative.
Example
Given 1->2->3->4->5->null and k=2
return 4->5->1->2->3->null
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: /** * @param head: the list * @param k: rotate to the right k places * @return: the list after rotation */ int ListCount(ListNode* head) { if (!head) return 0; int count = 1; ListNode *pCurNode = head; while (pCurNode->next) { pCurNode = pCurNode->next; count++; } return count; } ListNode *rotateRight(ListNode *head, int k) { // write your code here if (!head) return NULL; if (k == 0) return head; int nodeCount = ListCount(head); if (nodeCount == 1) return head; ListNode* pFastNode = head; ListNode* pSlowNode = head; ListNode fakeHead = ListNode(-1); ListNode* pPreNode = &fakeHead; pPreNode->next = head; k = k%ListCount(head); for (int i=1; i<=k-1; i++) { if (pFastNode->next) { pFastNode = pFastNode->next; } else { return head; } } while (pFastNode->next != NULL) { pFastNode = pFastNode->next; pSlowNode = pSlowNode->next; pPreNode = pPreNode->next; } pFastNode->next = head; pPreNode->next = NULL; return pSlowNode; }};
0 0
- lintcode:Rotate List
- [Lintcode]Rotate List旋转链表
- [Lintcode]Rotate Image
- 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
- 如何让scrollView拥有单方向的bounce
- 建立第一个App-整理笔记
- 初学Android,短信管理器之发送短信(六十五)
- 培训2
- BZOJ 3668: [Noi2014]起床困难综合症
- lintcode:Rotate List
- thinkphp备忘
- android studio连接汇总
- Webx中自定义Valve
- C#简易教程
- hdu1223(贪心+并查集=kruskal算法)
- Android系统原理与源码分析(1):利用Java反射技术阻止通过按钮关闭对话框
- hihoCoder 1170 机器人 (状压dp)
- sql 分组取最新的数据