Java for LeetCode 061 Rotate List
生活随笔
收集整理的這篇文章主要介紹了
Java for LeetCode 061 Rotate List
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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.
解題思路:
只需找到對(duì)應(yīng)的位置,然后指向head,接著把之前節(jié)點(diǎn)指向null即可,注意k可以取大于length的值,所以k%=length,JAVA實(shí)現(xiàn)如下:
public ListNode rotateRight(ListNode head, int k) {if(head==null||head.next==null)return head;ListNode temp=head;int length=1;while(temp.next!=null){temp=temp.next;length++;}if(k==length)return head;temp.next=head;temp=head;for(int i=1;i<length-k;i++)temp=temp.next;head=temp.next;temp.next=null;return head;}?
轉(zhuǎn)載于:https://www.cnblogs.com/tonyluis/p/4506869.html
總結(jié)
以上是生活随笔為你收集整理的Java for LeetCode 061 Rotate List的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 倍福TWinCAT3安装记录
- 下一篇: Java进程占用CPU资源过多分析