【LeetCode】24. Swap Nodes in Pairs C語言

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

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
//方法1
struct ListNode* swapPairs(struct ListNode* head) {
    struct ListNode *dummy=(struct ListNode*)malloc(sizeof(struct ListNode));
    dummy->next = head;
    struct ListNode *cur=dummy;
    
    while(cur->next!=NULL && cur->next->next!=NULL)
    {
        struct ListNode *first=cur->next;
        struct ListNode *second=cur->next->next;
        first->next = second->next;
        cur->next=second;
        second->next=first;
        cur=cur->next->next;
    }
    return dummy->next;
}    
 
//方法2 遞歸
struct ListNode* swapPairs(struct ListNode* head) {
    if(head == NULL || head->next ==NULL) return head;
    struct ListNode *p=head->next;
    
    head->next=swapPairs(head->next->next);
    p->next=head;
    return p;
}


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