iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 15
0
自我挑戰組

刷題記錄與人生分享系列 第 15

DAY15 Swap Nodes in Pairs

  • 分享至 

  • xImage
  •  

題目:

https://leetcode.com/problems/swap-nodes-in-pairs/
一個連結串列,交換2個相鄰的節點並返回首節點。

解題思路:

先用p1、p2紀錄首節點跟下一個節點,進行交換後temp用來記錄下一個要交換的節點,直到條件符合時跳出迴圈。

C版本:

struct ListNode* swapPairs(struct ListNode* head) {
    
    if (head == NULL || head -> next == NULL )
     return head;
    
    struct ListNode *p1 = head;
    struct ListNode *p2 = head -> next;
    struct ListNode *result = p2;
    struct ListNode *temp = NULL ;
    while (p1 != NULL && p2 != NULL )
    {
        p1 -> next = p2 -> next;
        p2 -> next = p1;
        
        if (temp != NULL )
                temp -> next = p2;
        temp = p1;
        if (p1 -> next != NULL && p1 -> next -> next != NULL )
            {
                p1 = p1 -> next;
                p2 = p1 -> next;
            }
            else 
                break ;
    }
    return result;
}

Javascript版本:

var swapPairs = function(head) {
    if (head == null || head.next == null )
     return head;
    var p1 = new ListNode(0);
    var p2 = new ListNode(0);
    var result = new ListNode(0);
    var temp = new ListNode(0);
    
    p1 = head;
    p2 = head.next;
    result = p2;
    temp = null;
    
    while (p1 != null && p2 != null )
    {
        p1.next = p2.next;
        p2.next = p1;
        
        if (temp != null )
            temp.next = p2;
        temp = p1;
        if (p1.next != null && p1.next.next != null )
            {
                p1 = p1.next;
                p2 = p1.next;
            }
            else 
                break ;
    }
    return result;
};

程式Github分享:

https://github.com/SIAOYUCHEN/leetcode

相似主題分享:

https://ithelp.ithome.com.tw/users/20100009/ironman/2500
https://ithelp.ithome.com.tw/users/20113393/ironman/2169
https://ithelp.ithome.com.tw/users/20107480/ironman/2435
https://ithelp.ithome.com.tw/users/20107195/ironman/2382
https://ithelp.ithome.com.tw/users/20119871/ironman/2210
https://ithelp.ithome.com.tw/users/20106426/ironman/2136

本日分享:

Accept yourself and experience the perfection in imperfections in life
接受自己,體會生命裡不完美中的完美


上一篇
DAY14 Rotate Array
下一篇
DAY16 Merge Two Sorted Lists
系列文
刷題記錄與人生分享34
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言