LeetCode OJ 61. Rotate List 考虑边界条件
Posted bruce128
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode OJ 61. Rotate List 考虑边界条件相关的知识,希望对你有一定的参考价值。
题目链接:https://leetcode.com/problems/rotate-list/
61. Rotate List
My SubmissionsTotal 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 Similar Problems
Have you met this question in a real interview?
Yes
No
题目不难,但是边界条件十分让人抓狂。重点考虑以下三个边界case:
- 右移的k值比链表的本身长度还要长。这个时候需要对长度取模。
- k=0时,直接返回head即可
- 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 考虑边界条件的主要内容,如果未能解决你的问题,请参考以下文章