1. 程式人生 > >[Leetcode24]兩兩交換連結串列中的節點

[Leetcode24]兩兩交換連結串列中的節點

給定一個連結串列,兩兩交換其中相鄰的節點,並返回交換後的連結串列。

說明:

  • 你的演算法只能使用常數的額外空間。
  • 你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。

python:

這道題難度不大,我個人覺得難點在於理解連結串列的複製原理。主要也就是建立一個臨時節點進行交換去解決這道題。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None or head.next == None:
            return head
        if head.next :
            begin = ListNode(head.next.val)
            head.next = head.next.next
            begin.next = head
        while head.next :
            if head.next.next :
                temp = ListNode(head.next.val)
                head.next = head.next.next
                temp.next = head.next.next
                head.next.next = temp
                head = temp
            else:
                break
        return begin

            

C++:

C++相對於python來說要注意的是變數的作用域,要在函式作用域裡建立一個res作為開頭存下來方便後續輸出。 

/**
 * 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) {
        ListNode* res = new ListNode(0);
        if(head == NULL || head->next == NULL) return head;
        if(head->next){
            ListNode* begin = new ListNode(head->next->val);
            head->next = head->next->next;
            begin->next = head;
            res = begin;
        }
        while(head->next){
            if(head->next->next){
                ListNode* temp = new ListNode(head->next->val);
                head->next = head->next->next;
                temp->next = head->next->next;
                head->next->next = temp;
                head = temp;
            }
            else break;
        }
        return res;
    }
};