【Leetcode】Rotate List
2015-07-29 23:06
309 查看
【题目】
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
【思路】
实质就是n-k个元素挪到了链子的前面, 第n-k个元素变成新head,最后一个元素链接当前的head
注意起始边缘条件,如果head是空,只有一个元素,或者k=0,都只要返回head就可以。
首先找到这个list的长度 n, 方法就是遍历一遍咯。
得到长度以后,我们就知道是哪后几个挪过来。
注意细节!!:
k的值有可能大于n!! 所以 step = n - n%k,
找到最后一个元素之后,最后一个元素就可以直接连接到head了
这时候可以继续用h这个变量,因为已经连接上head了,而且位置在head之前,正好!可以经过step步以后达到新head的前一个,然后把h .next赋给新的headNode,在变成空。(因为队尾下一个要赋值为空!)就OK了!
【代码】
/**
* 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) {
if(head == null || head.next == null || k ==0) return head;
ListNode h = head;
int n = 1;
while(h.next != null){
n++;
h = h.next;
}
<span style="background-color: rgb(255, 255, 153);"> h.next = head;</span>
int step = n - k%n;
for(int i = 0 ; i <step;i++){
h = h.next;
}
ListNode NHead = h.next;
h.next = null;
return NHead;
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->NULLand k =
2,
return
4->5->1->2->3->NULL.
【思路】
实质就是n-k个元素挪到了链子的前面, 第n-k个元素变成新head,最后一个元素链接当前的head
注意起始边缘条件,如果head是空,只有一个元素,或者k=0,都只要返回head就可以。
首先找到这个list的长度 n, 方法就是遍历一遍咯。
得到长度以后,我们就知道是哪后几个挪过来。
注意细节!!:
k的值有可能大于n!! 所以 step = n - n%k,
找到最后一个元素之后,最后一个元素就可以直接连接到head了
这时候可以继续用h这个变量,因为已经连接上head了,而且位置在head之前,正好!可以经过step步以后达到新head的前一个,然后把h .next赋给新的headNode,在变成空。(因为队尾下一个要赋值为空!)就OK了!
【代码】
/**
* 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) {
if(head == null || head.next == null || k ==0) return head;
ListNode h = head;
int n = 1;
while(h.next != null){
n++;
h = h.next;
}
<span style="background-color: rgb(255, 255, 153);"> h.next = head;</span>
int step = n - k%n;
for(int i = 0 ; i <step;i++){
h = h.next;
}
ListNode NHead = h.next;
h.next = null;
return NHead;
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解