算法系列——Rotate List
来源:互联网 发布:如何在七天网络查分 编辑:程序博客网 时间:2024/06/05 08:12
题目描述
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%len (len表示链表长度)操作。
首先应该求出链表长度len,然后从头移动指针,移动到正数 第 len-k个结点,那个len-k+1 就是倒数第k个结点,然后进行对应的指针操作即可。
程序实现
public class Solution { public ListNode rotateRight(ListNode head, int k) { if(head==null||head.next==null||k<=0) return head; ListNode p=head; int len=1; //取得链表长度 while(p.next!=null){ p=p.next; len++; } p.next=head; k=k%len; for(int i=0;i<len-k;i++) p=p.next; //p指向第len-k个结点 head=p.next; p.next=null; return head; }}
阅读全文
0 0
- 算法系列——Rotate List
- LeetCode——Rotate List
- LeetCode61——Rotate List
- Algorithms—61.Rotate List
- 算法系列--Rotate Image
- LeetCode算法题目:Rotate List
- 算法系列——Reverse Linked List
- 算法系列——Linked List Cycle
- 算法系列——Sort List
- 算法系列——Reorder List
- 算法系列——Partition List
- leetcode 061 —— Rotate List
- LeetCode题解——Rotate List
- LeetCode OJ——Rotate List
- Leetcode题集——rotate-list
- Leetcode——61. Rotate List
- 2.2.6—单链表—Rotate List
- LeetCode]—Rotate List 循环右移链表
- 7_18|C语言|判断浮点数等于0|浮点数的保存形式
- spring事务管理 @Transactional
- js使用方式
- Android Studio 中出现错误Failed to resolve: com.android.support.constraint:constraint-layout:1.0.2
- cdh完美集成kafka
- 算法系列——Rotate List
- Windows下Nginx+Tomcat整合的安装与配置
- MySQL 同表一个字段赋值给另一个字段
- 几个好用的terminal快捷键
- localStorage的过期时间设置的方法?
- python数据挖掘笔记(2)—模型建立
- 时钟周期,机器周期,指令周期的区别
- Spring事务管理中@Transactional的propagation参数
- 记录一些以后要拜读的java书籍