iT邦幫忙

2021 iThome 鐵人賽

DAY 6
1
AI & Data

想到甚麼打甚麼系列 第 6

找LeetCode上簡單的題目來撐過30天啦(DAY6)

今天嘗試了前幾天被我放棄的題目,過一兩天後果然比較有感覺,花了一點時間還是完成了呢,心情不錯/images/emoticon/emoticon07.gif

題號:61 標題:Rotate List 難度:Medium

Given the head of a linked list, rotate the list to the right by k places.

Example 1:

Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]

Example 2:

Input: head = [0,1,2], k = 4
Output: [2,0,1]

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吧?


上一篇
找LeetCode上簡單的題目來撐過30天啦(DAY5)
下一篇
找LeetCode上簡單的題目來撐過30天啦(DAY7)
系列文
想到甚麼打甚麼30

1 則留言

0
lhttfy
iT邦新手 5 級 ‧ 2021-09-21 20:55:55

OK啦

我要留言

立即登入留言