【leetcode】Rotate List
2016-06-02 21:36
447 查看
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
思路:
将链表尾部和头部连起来,顺便算出链表长度len
计算k% len,把尾指针移动到位,然后断开
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k)
{
if (head == NULL)
return head;
ListNode* tail = head;
ListNode* newhead = head;
int len = 1;
while (tail->next != NULL)
{
tail = tail->next;
++len;
}
tail->next = head;
k %= len;
for (int i = 0; i < len - k; ++i)
{
tail = tail->next;
}
newhead = tail->next;
tail->next = NULL;
return newhead;
}
};
For example:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL.
思路:
将链表尾部和头部连起来,顺便算出链表长度len
计算k% len,把尾指针移动到位,然后断开
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k)
{
if (head == NULL)
return head;
ListNode* tail = head;
ListNode* newhead = head;
int len = 1;
while (tail->next != NULL)
{
tail = tail->next;
++len;
}
tail->next = head;
k %= len;
for (int i = 0; i < len - k; ++i)
{
tail = tail->next;
}
newhead = tail->next;
tail->next = NULL;
return newhead;
}
};
相关文章推荐
- oracle-union order by rownum排序与取数
- Android解析XML(PULL方式)
- 第二阶段冲刺第九天
- stm32 usb error : identifier "bool" is undefined
- stm32 usb error : identifier "bool" is undefined
- postgresql create db and table
- Invalid ADAPTORNAME specified. Type 'imaqhwinfo' for a list of available ADAPTORNAMEs. Image acquis
- IOS 封装button
- ToolBar的进阶详细使用
- K-mediods(K中心点)算法
- 网络编程问题小结
- android开发笔记之网络编程—使用HTTP进行网络编程
- 【转载】DXUT进阶
- 码神学Java第二天
- Thread.interrupt与LockSupport
- 请别让众筹成为网络乞讨平台
- 【无人驾驶系列】基于ROS的无人驾驶系统
- 165. Compare Version Numbers
- [MD5变形算法练习] AutoRun Design Specialty算法分析
- 第二个冲刺