如何用C++代碼實現(xiàn)成對交換節(jié)點

本篇內(nèi)容介紹了“如何用C++代碼實現(xiàn)成對交換節(jié)點”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!

創(chuàng)新互聯(lián)是一家專注于成都網(wǎng)站設(shè)計、成都做網(wǎng)站與策劃設(shè)計,安居網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)做網(wǎng)站,專注于網(wǎng)站建設(shè)十年,網(wǎng)設(shè)計領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:安居等地區(qū)。安居做網(wǎng)站價格咨詢:13518219792

成對交換節(jié)點

Example:

Given

1->2->3->4

, you should return the list as

2->1->4->3.

這道題不算難,是基本的鏈表操作題,我們可以分別用遞歸和迭代來實現(xiàn)。對于迭代實現(xiàn),還是需要建立 dummy 節(jié)點,注意在連接節(jié)點的時候,最好畫個圖,以免把自己搞暈了,參見代碼如下:

解法一:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode *dummy = new ListNode(-1), *pre = dummy;
        dummy->next = head;
        while (pre->next && pre->next->next) {
            ListNode *t = pre->next->next;
            pre->next->next = t->next;
            t->next = pre->next;
            pre->next = t;
            pre = t->next;
        }
        return dummy->next;
    }
};

遞歸的寫法就更簡潔了,實際上利用了回溯的思想,遞歸遍歷到鏈表末尾,然后先交換末尾兩個,然后依次往前交換:

解法二:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (!head || !head->next) return head;
        ListNode *t = head->next;
        head->next = swapPairs(head->next->next);
        t->next = head;
        return t;
    }
};

解法三:

class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = head.next;
        head.next = swapPairs(newHead.next);
        newHead.next = head;
        return newHead;
    }
}

“如何用C++代碼實現(xiàn)成對交換節(jié)點”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

當前文章:如何用C++代碼實現(xiàn)成對交換節(jié)點
地址分享:http://muchs.cn/article10/pipsdo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站、電子商務(wù)、小程序開發(fā)定制網(wǎng)站、網(wǎng)站收錄、軟件開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)