您的位置:首页 > 其它

LeetCode 60 Rotate List

2014-06-21 00:19 232 查看
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
.

public class Solution {
	public ListNode rotateRight(ListNode head, int n) {
		if (n < 1 || head == null)
			return head;

		ListNode dumny = new ListNode(-1);
		ListNode p = head;
		int counter = 1;
		while (p.next != null) {
			p = p.next;
			counter++;
		}
		p.next = head;

		int i = 1;
		p = head;
		while (i < (counter - n % counter)) {
			p = p.next;
			i++;
		}
		
		dumny.next = p.next;
		p.next = null;
		return dumny.next;
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: