#LeetCode:24. Swap Nodes in Pairs

利用兩個指標指向 Linked List 兩個欲交換的節點前面做交換,並巡覽整個 List 做一次即可。

C++(0ms)

/*******************************************************/
/* LeetCode 24. Swap Nodes in Pairs                    */
/* Author: Maplewing [at] knightzone.studio            */
/* Version: 2018/10/18                                 */
/*******************************************************/
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
  ListNode* swapPairs(ListNode* head) {
    if(head == NULL) return head;

    ListNode dummyHead(-1);
    dummyHead.next = head;

    ListNode* previous = &dummyHead;
    ListNode* current = dummyHead.next;

    while(current != NULL){
      if(current->next == NULL) break;
      previous->next = current->next;
      current->next = previous->next->next;
      previous->next->next = current;

      previous = current;
      current = current->next;
    }

    return dummyHead.next;
  }
};
廣告

Comment

There is no comment on this post. Be the first one.

發表迴響

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料

%d 位部落客按了讚: