首页 > 其他 > 详细

LeetCode | Rotate List

时间:2014-03-18 11:50:05      阅读:210      评论:0      收藏:0      [点我收藏+]

题目

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.

分析

先得到链表长度len,n对len取余就是需要右转长度(也可以不要长度,就是指针移动n次找到剪切位置,但是如果n过大就悲剧了),然后找到剪切位置,这里依然用个哨兵简化代码。

代码

public class RotateList {
	public ListNode rotateRight(ListNode head, int n) {
		if (head == null || n == 0) {
			return head;
		}
		ListNode tail = head;
		int len = 1;
		while (tail.next != null) {
			tail = tail.next;
			++len;
		}
		n = len - n % len;
		if (n == len) {
			return head;
		}
		ListNode dummy = new ListNode(0);
		dummy.next = head;
		head = dummy;
		for (int i = 0; i < n; ++i) {
			head = head.next;
		}
		tail.next = dummy.next;
		dummy.next = head.next;
		head.next = null;
		return dummy.next;
	}
}


LeetCode | Rotate List,布布扣,bubuko.com

LeetCode | Rotate List

原文:http://blog.csdn.net/perfect8886/article/details/21414629

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!