leetcode解题方案--061--RotateList
来源:互联网 发布:linux菜鸟私房菜 编辑:程序博客网 时间:2024/06/01 09:40
题目
Given a list, rotate the list to the right by k places, where k is non-negative.
Example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
分析
这道题其实在考察求倒数第k个链表节点。
两个指针同时移动。然后。。。。
没什么难度。
让人觉得难过的点是,这个k可能大于数组长度,因此我先求了数组长度,然后取余。
还有一种思路是把首尾连起来 组成一个环,思路大致相同。如果k依然大于零而已经到末尾,则从头开始,继续循环。
public static ListNode rotateRight(ListNode head, int k) { if (head == null) { return null; } ListNode last = head; int length = 0; while (last != null) { length++; last = last.next; } k = k % length; last = head; ListNode lastk = head; while (k-- > 0) { last = last.next; } if (last == null) { return head; } while (last.next != null) { last = last.next; lastk = lastk.next; } last.next = head; ListNode ret = lastk.next; lastk.next = null; return ret; }
阅读全文
0 0
- leetcode解题方案--061--RotateList
- Leetcode解题-链表(2.2.6)RotateList
- LeetCode(60)RotateList
- leetcode解题方案--001--TwoSum
- leetcode解题方案--002--AddTwoNumbers
- leetcode解题方案--003--LongestSubstringWithoutRepeatingCharacters
- leetcode解题方案--004--MedianofTwoSortedArrays
- leetcode解题方案--039-- CombinationSum
- leetcode解题方案--040-- CombinationSum
- leetcode解题方案--046--Permutations
- leetcode解题方案--055--jumpGame
- [Leetcode] Duplicate Emails 我的解题方案
- leetcode解题方案--005--Longest Palindromic Substring
- leetcode解题方案--012--Integer to Roman
- leetcode解题方案--013--Roman to Integer
- leetcode解题方案--014--Longest Common Prefix
- leetcode解题方案--015--3 sum
- leetcode解题方案--016--3 sum closest
- php编辑器notepad++ 推荐一款非常好看主题和字体
- sdnu-并查集-weeklyexam ——H
- vue中calss 动态绑定实现下拉列表
- Stepper Motor Driving Patterns
- 数组名a和&a的区别
- leetcode解题方案--061--RotateList
- python学习笔记 第七章(二)
- IA-32 Intel手册学习笔记(三)任务切换
- sdnu-并查集-weeklyexam ——I
- 告别session jwt使用初尝试
- 448FindAllNumbersDisappearedInAnArray
- 计算机网络中,16位校验和的实现
- ACM 比赛如何正确开局、队员如何分工、如何把状态调整到最佳?
- zk框架