【LeetCode】 61. Rotate List C語言

LeetCode解題心得,歡迎交流! 第二日 


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* rotateRight(struct ListNode* head, int k) {
    if(head == NULL) return head;
    
    struct ListNode *new_head=head;
    struct ListNode *tail=head;
    
    int i,length=1; 
    while(tail->next !=NULL)
    {
        length++;
        tail=tail->next;
    }
    
    tail->next=head;  // circle the link
    
    if(k=k%length)
    {
        for(i=0;i<length-k;i++)
        {
            tail=tail->next;
        }
    }
    
    new_head=tail->next;
    tail->next=NULL;
    return new_head;
}


發佈了30 篇原創文章 · 獲贊 4 · 訪問量 8827
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章