Rotate List
来源:互联网 发布:手机淘宝松子类目 编辑:程序博客网 时间:2024/06/05 12:01
一、问题描述
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 % size == 0 || size == 1
时不翻转链表。
三、代码
class Solution {public: ListNode* rotateRight(ListNode* head, int k) { if( k == 0) return head; int size = 0; ListNode* p = head; ListNode* q = head; while(p){ ++size; p = p -> next; } if(size == 0) return NULL; if(k % size == 0 || size == 1) return head; p = head; int k1 = k % size; int end = size - k1; while(--end) p = p -> next; q = p -> next; p -> next = NULL; p = q; while(--k1) p = p -> next; p -> next = head; return q; }};
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
- Android:layout_weight
- 使用视频作为网页背景的技术探讨
- unix文件描述符——socket
- 史上最全的“大数据”学习资源(上)
- javaSE学习笔记——接口
- Rotate List
- Escape noise
- LINUX中的rfcomm命令工具的使用
- 史上最全的“大数据”学习资源(下)
- Qt自定义控件的创建与初步使用(一)之自定义控件的创建步骤
- 【方法】使C++的cout能在不设置locale的情况下正确输出wchar_t Unicode字符串
- hive启动错误:[ERROR] Terminal initialization failed; falling back to unsupported
- 剑指offer45--找到数组重复元素
- Your binary is not optimized for iPhone 5