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
return
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));
}
}
For example:
Given
1->2->3->4->5->NULLand 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));
}
}
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树
- [原创]java局域网聊天系统