博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: Rotate List
阅读量:4665 次
发布时间:2019-06-09

本文共 1266 字,大约阅读时间需要 4 分钟。

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 }

 

 

转载于:https://www.cnblogs.com/EdwardLiu/p/3805191.html

你可能感兴趣的文章
10套免费的响应式布局 Bootstrap 模版
查看>>
Tomcat 性能优化之APR插件安装 -- [转]
查看>>
WebClient 调用api
查看>>
《Spring实战》-2
查看>>
php中静态方法的使用
查看>>
转:影响数据检索效率的几个因素
查看>>
Xamarin.Android 的照相機使用
查看>>
全文检索-Elasticsearch (三) DSL
查看>>
MySQL 查询缓存
查看>>
文档对象模型(DOM)系列一:DOM基础
查看>>
js代码收集(1)
查看>>
二:输入10个整数,将它们从大到小排序后输出。
查看>>
mongodb删除重复数据
查看>>
项目中遇到的问题:前台 disabled 与 后台disabled
查看>>
BZOJ1801:[Ahoi2009]chess 中国象棋
查看>>
多态(3)面向对象的三大特征之三
查看>>
简单高效的代码部署方法
查看>>
[Spring框架]Spring JDBCTmplate基础入门总结.
查看>>
ecshop修改产品详情 折扣倒计时时间
查看>>
Core Java Volume I — 4.10. Class Design Hints
查看>>