61. Rotate List
来源:互联网 发布:大数据技术案例 编辑:程序博客网 时间:2024/06/07 13:05
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个元素旋转到链表前面。
需要注意的一点是,k可以大于列表中元素个数,此时k=k%num;(num为列表中元素个数)
解题思路:
1.计算列表长度,即元素个数num。
2.循环找到第num-k个元素和第num-k+1个元素,并将第num-k个元素的next值置为null。
3.从第num-k+1个元素开始循环,直到列表末尾元素,将其next值置为head(head为列表头元素)。
4.返回第num-k+1个元素。完成!
下面贴代码:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode rotateRight(ListNode head, int k) { int num= 0; ListNode h = head; //计算列表长度 while(h != null){ num++; h = h.next; } if(num<2) return head; k = k%num; //计算k的值 if(k==0 || k==num) return head; ListNode h1 = head; for(int i=0;i<num-k-1;i++){ //找到第num-k个元素 h1 = h1.next; } h = h1.next; //第num-k+1个元素 h1.next = null; h1 = h; while(h1.next != null){ //找到末尾元素 h1 = h1.next; } h1.next = head; return h; }}
阅读全文
0 0
- [LeetCode]61.Rotate List
- 61. Rotate List
- LeetCode --- 61. Rotate List
- [Leetcode] 61. Rotate List
- 61. Rotate List
- [leetcode] 61.Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List
- 61. Rotate List
- 61. Rotate List LeetCode
- leetcode 61. Rotate List
- 61. Rotate List
- 61. Rotate List
- 61. Rotate List
- <c:set>标签的简单使用
- 使用requests和re库对淘宝商品信息进行定向爬取
- 【mySql数据库初识】
- POJ 1543 Perfect Cubes 笔记
- Unhealthy Nodes导致计算能力下降
- 61. Rotate List
- U盘安装CentOS7是报错:/dev/root not exist
- 状态图(Statechart Diagram)
- 【机房重构】导出到Excel
- c++使用二重指针实现矩阵的储存释放和乘法
- 0、注意事项
- Climbing Worm
- 嵌入式简答试题及答案汇总
- [笔记]C++ Empty Class(analysis construcor and desturctor)