[LeetCode] Rotate List
来源:互联网 发布:微信骚扰软件 编辑:程序博客网 时间:2024/06/05 16:26
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
.
/** * 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 == nullptr || k <= 0) return head; int len = listLength(head); k %= len; if(k == 0) return head; ListNode *p = head, *new_head = head, *new_end = head; for(int i = 0; i < k; i++) p = p->next; while(p->next) { p = p->next; new_end = new_end->next; } new_head = new_end->next; new_end->next = nullptr; p->next = head; return new_head; } int listLength(ListNode *head) { int len = 0; while(head) { len++; head = head->next; } return len; }};
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
- 关于类的合理设计
- easyui datagrid的多选问题
- unity记录
- Razor语法快速参考
- java向上转型和向下转型
- [LeetCode] Rotate List
- nagios 安装配置(包括nrpe端)全 (五)
- java.lang.NoClassDefFoundError: org/objectweb/asm/Type 错误
- Oracle体系结构
- android CVArrays
- Android权限之packages.xml解析
- 聊聊高并发(七)实现几种自旋锁(二)
- Android recovery UI实现分析
- Launcher源码学习记录(一)