• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Rotate List

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.

Anaylisis: Linked List题目的做法其实比较固定,就是Runner Technique(Two pointer) 方法加上 Dummy Node(设置一个head之前的虚假节点)两种方法,这道题就这样搞一搞就出来了。

需要注意的是:处理null 输入需要特别考虑,然后,需要找到新的linked list的头

第二遍做法:注意15行需要特别处理,wrap up了之后n=0的情况

 1 public class Solution {
 2     public ListNode rotateRight(ListNode head, int n) {
 3         if (head == null) return null;
 4         ListNode dummy = new ListNode(-1);
 5         dummy.next = head;
 6         ListNode cursor = dummy;
 7         ListNode walker = dummy;
 8         ListNode runner = dummy;
 9         int count = 0;
10         while (cursor.next != null) {
11             cursor = cursor.next;
12             count ++;
13         }
14         n %= count;
15         if (n == 0) return head;
16         while (n > 0) {
17             runner = runner.next;
18             n--;
19         }
20         while (runner.next != null) {
21             runner = runner.next;
22             walker = walker.next;
23         }
24         dummy.next = walker.next;
25         walker.next = runner.next;
26         runner.next = head;
27         return dummy.next;
28     }
29 }

 

 

posted @ 2014-06-23 23:28  neverlandly  阅读(255)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3