Java for LeetCode 061 Rotate List
生活随笔
收集整理的這篇文章主要介紹了
Java for LeetCode 061 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.
解題思路:
只需找到對應的位置,然后指向head,接著把之前節點指向null即可,注意k可以取大于length的值,所以k%=length,JAVA實現如下:
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;}?
轉載于:https://www.cnblogs.com/tonyluis/p/4506869.html
總結
以上是生活随笔為你收集整理的Java for LeetCode 061 Rotate List的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 倍福TWinCAT3安装记录
- 下一篇: UITextView 响应 键盘的ret