今天嘗試了前幾天被我放棄的題目,過一兩天後果然比較有感覺,花了一點時間還是完成了呢,心情不錯
題號:61 標題:Rotate List 難度:Medium
Given the head of a linked list, rotate the list to the right by k places.
Constraints:
• The number of nodes in the list is in the range [0, 500].
• -100 <= Node.val <= 100
• 0 <= k <= 2 * 109
我的程式碼
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
ListNode result = new ListNode();
ListNode temp = new ListNode();
ListNode v = new ListNode();
int i=0,j=0,count=1;
if(head== null || k==0 || head.next==null){
return head;
}
for(i=0;i<k;i++){
while(true){
if(head.next==null) {
temp = head;
break;
}else if(j==0){
result = head;
j++;
}
head =head.next;
count++;
}
System.out.println(count);
v = result;
while(true){
if(result.next==temp) {
result.next = null;
break;
}
result =result.next;
}
temp.next= v;
j=0;
head = temp;
if(i==0){
if(k/count>count){
k = k%count;
}else if( k%count==0){
k = count;
}
}
}
return temp;
}
}
花比較久的時間在
了解此題的Definition for singly-linked list,基本資料結構的概念是有的,但從來沒有實際碰到過,所以花了點時間了解一下如何達成我要得目的,不能回頭真的是好煩呀
DAY6心得
我對於內容越來越偷懶了,反正也是想讓自己一直有在進步而已,應該OK吧?