4.29 leetcode -29 rotate-list
来源:互联网 发布:淘宝默认邮箱 编辑:程序博客网 时间:2024/06/05 14:52
题目描述
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULLand k =2,
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.
这个问题,我同学和我说,面试出过问题。
需要小心的点是,k > 链表长度,此时相当于又一个mod过程。
思路不难,两个指针,前后走就行。
/** * 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) { ListNode *pToEnd = head; ListNode *pNewEnd = head; ListNode *pNewHead; if(head == NULL) return NULL; int i = 0; for(; i < k ;i ++) { if(pToEnd->next == NULL)//k大于链表长度的话 pToEnd = head; else pToEnd = pToEnd->next; } while(pToEnd->next != NULL) { pToEnd = pToEnd->next; pNewEnd = pNewEnd->next; } pToEnd->next = head; pNewHead = pNewEnd->next; pNewEnd->next = NULL; return pNewHead; }};
阅读全文
0 0
- 4.29 leetcode -29 rotate-list
- [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
- MySql 常见错误代码大全
- 链表排序
- 微信语音上传下载
- Linux添加、删除FTP用户并设置权限
- 构造完全二叉树,并按行从左到右输出
- 4.29 leetcode -29 rotate-list
- 简单的mysql增删改查(1)
- form表单中用户名和密码文字对齐
- serialVersionUID作用
- osmdroid 离线地图加载
- 银行家算法
- 开启CORS跨域访问
- 资讯精选 | 物联网时代半导体制造设备小型化大势所趋
- Oracle与Sql Server复制表结构及数据