LeetCode.61 Rotate List
来源:互联网 发布:python与 shell 编辑:程序博客网 时间:2024/06/05 00:31
题目:
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
.
分析1(实测较分析2快,易理解):
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */class Solution { public ListNode rotateRight(ListNode head, int k) { //给定链表,对调末尾k个节点 //求出链表长度 //需要考虑k大于链表长度的情况,例如:输入【1,2】3 输出【2,1】,输入【1,2】 4 输出【1,2】 int len=listLength(head); if(head==null||k<=0)return head; //考虑k大于链表节点大的情况 k=k%len; //链表长度减去k则为前半部分 ListNode dummy=new ListNode(0); ListNode res=dummy; dummy.next=head; ListNode cur=head,pre=dummy; for(int i=len-k;i>0;i--){ pre=pre.next; cur=cur.next; } //调换后半部k个节点 while(cur!=null){ pre.next=cur.next; cur.next=dummy.next; dummy.next=cur; dummy=dummy.next; cur=pre.next; } return res.next; } public int listLength(ListNode head){ ListNode pre=head; int count=0; while(pre!=null){ count++; pre=pre.next; } return count; }}分析2:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */class Solution { public ListNode rotateRight(ListNode head, int k) { //首先要看k是否大于链表的长度,若是大于长度,则对其求余k%len的位置旋转 //最后next指向head,形成一个环,之后遍历新的head的前一个节点的next赋值null,最后返回head if(head==null||k<0)return head; int count=1; ListNode cur=head; while(cur.next!=null){ count++; cur=cur.next; } //获取右边开始节点的下标 k=k%count; //将最后一个节点next指向head,形成环 cur.next=head; //接下来遍历节点数 int num=count-k; for(int i=0;i<num;i++){ cur=cur.next; } head=cur.next; //断链 cur.next=null; return head; }}
阅读全文
0 0
- LeetCode 61: Rotate List
- [leetcode 61] Rotate List
- [leetcode #61]Rotate List
- leetcode || 61、Rotate List
- leetcode[61]:Rotate List
- LeetCode 61: Rotate List
- LeetCode(61) Rotate List
- LeetCode 61 Rotate List
- leetcode 61: Rotate List
- Leetcode#61||Rotate List
- [Leetcode]#61 Rotate List
- leetcode 61:Rotate List
- 【leetcode】【61】Rotate List
- 【LeetCode-61】Rotate List
- LeetCode 61 - Rotate List
- ( Leetcode 61 ) Rotate List
- leetcode-Rotate List-61
- LeetCode 61 Rotate List
- 不能覆盖的日记
- ST 求区间最大值板子
- FreeMarker 模版框架学习
- 字符串
- win10安装apache 2.4 + php7
- LeetCode.61 Rotate List
- 搭建linux服务器集群,简单实现,负载均衡,动静分离,数据主从复制,分布式缓存,共享session回话。
- java学习笔记(4)
- python %r 和%s的区别
- 手把手教你AndroidStudio多渠道打包
- 匿名内部类
- AOV网和Topo排序
- iOS notification的优势及缺点
- javaEE全套视频