您的位置:首页 > 编程语言 > Java开发

LeetCode_61---Rotate List

2015-06-28 11:46 513 查看
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
.

Hide Tags
 Linked List Two
Pointers

Code:

/*题目大意
给出一个单链表,和一个K值,根据K值往右旋转,例如:

*/

public class LeetCode61 {
public static class ListNode {
int val;
ListNode next;

ListNode(int x) {
val = x;
}

public String toString() {
return Integer.toString(val) + " " + next;
}
}

// 324msAC----http://www.cnblogs.com/kaituorensheng/p/3647668.html
public static ListNode rotateRight(ListNode head, int k) {
if (k <= 0 || head == null) {
return head;
}
ListNode tempA = head;
int sum = 1;
while (head.next != null) {
head = head.next;
sum++;
}
System.out.println("sum: " + sum);
head.next = tempA;
head = tempA;
k = sum - k % sum;
System.out.println("k: " + k);
int i = 0;
while (i < k) {
tempA = head;
head = head.next;
i++;
}
tempA.next = null;
return head;
}

public static void main(String[] args) {
ListNode head = new ListNode(0);
ListNode a = new ListNode(1);
ListNode b = new ListNode(2);
head.next = a;
a.next = b;
b.next = null;
int k = 4;
System.out.println("rotateRight: " + rotateRight(head, k));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode java 算法