【LeetCode】 25. Reverse Nodes in k-Group C語言

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



/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode* reverseKGroup(struct ListNode* head, int k) {
    if(head==NULL || head->next==NULL ||k<2) return head;
    struct ListNode *dummy=(struct ListNode *)malloc(sizeof(struct ListNode));
    dummy->next=head;
    
    struct ListNode *tail=dummy;
    struct ListNode *pre=dummy;
    struct ListNode *temp=NULL;
    int count ;
    
    while(1)
    {
        count = k;
        while(count>0 && tail != NULL)
        {
            count--;
            tail=tail->next;
        }
        
        if(tail == NULL ) break;
        
        head=pre->next;
        
        while(pre->next != tail)
        {
            temp=pre->next;
            pre->next=temp->next;
            temp->next=tail->next;
            tail->next=temp;
        }
        tail=head;
        pre=head;
    }
    return dummy->next;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章