码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ 61. Rotate List 考虑边界条件

时间:2016-06-16 14:44:39      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

    题目链接:https://leetcode.com/problems/rotate-list/

61. Rotate List

 My Submissions
Total Accepted: 71917 Total Submissions: 311425 Difficulty: Medium

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.

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No

Discuss Pick One


    题目不难,但是边界条件十分让人抓狂。重点考虑以下三个边界case:

  1. 右移的k值比链表的本身长度还要长。这个时候需要对长度取模。
  2. k=0时,直接返回head即可
  3. head为null时,返回null
    个人在使用单链表的时候,十分喜欢起哨兵作用的头结点。以下是我的AC代码:
public class RotateList {
	public static void main(String[] args) {
		ListNode h = new ListNode(1);
		h.next = null;
		rotateRight(h, 1);
	}

	public static ListNode rotateRight(ListNode head, int k) {
		if (head == null) return null;

		ListNode h = new ListNode(0);
		h.next = head;
		ListNode p1 = h, p2 = h, p = h;

		int len = 0;
		while (p.next != null) {
			p = p.next;
			len++;
		}
		k %= len;
		if (k == 0) return head;

		for (int i = 0; i < k; i++) p2 = p2.next;
		while (p2.next != null) {
			p1 = p1.next;
			p2 = p2.next;
		}

		h.next = p1.next;
		p2.next = head;
		p1.next = null;
		return h.next;
	}
}



LeetCode OJ 61. Rotate List 考虑边界条件

标签:

原文地址:http://blog.csdn.net/bruce128/article/details/51684656

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!