您的位置:首页 > 其它

Leetcode: Rotate List

2014-06-23 23:28 267 查看
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.


Anaylisis: Linked List题目的做法其实比较固定,就是Runner Technique(Two pointer) 方法加上 Dummy Node(设置一个head之前的虚假节点)两种方法,这道题就这样搞一搞就出来了。

需要注意的是:处理null 输入需要特别考虑,然后,需要找到新的linked list的头

第二遍做法:注意15行需要特别处理,wrap up了之后n=0的情况

public class Solution {
public ListNode rotateRight(ListNode head, int n) {
if (head == null) return null;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode cursor = dummy;
ListNode walker = dummy;
ListNode runner = dummy;
int count = 0;
while (cursor.next != null) {
cursor = cursor.next;
count ++;
}
n %= count;
if (n == 0) return head;
while (n > 0) {
runner = runner.next;
n--;
}
while (runner.next != null) {
runner = runner.next;
walker = walker.next;
}
dummy.next = walker.next;
walker.next = runner.next;
runner.next = head;
return dummy.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: