1. 程式人生 > >LeetCode24. 兩兩交換連結串列中的節點 Swap Nodes in Pairs(C語言)

LeetCode24. 兩兩交換連結串列中的節點 Swap Nodes in Pairs(C語言)

題目描述:

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

示例:

給定 1->2->3->4, 你應該返回 2->1->4->3.

說明:

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

題目解答:

方法1:遍歷交換

為了保證邏輯簡單,排除特殊情況,插入頭結點,另外使用三個指標。
執行時間0ms,程式碼如下。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* swapPairs(struct ListNode* head) { struct ListNode* front = (struct ListNode*)malloc(sizeof(struct ListNode)); front->next = head; struct ListNode *t = front, *t1 = NULL, *t2 = NULL; while(t && t->next && t->next->next) { t1 = t->
next; t2 = t1->next; t->next = t2; t1->next = t2->next; t2->next = t1; t = t1; } t = front->next; free(front); return t; }

方法2:遞迴法

但是遞迴使用了O(N)的空間,非O(1)。應該使用尾遞迴或者迭代
執行時間0ms,程式碼如下。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* swapPairs(struct ListNode* head) { if(head == NULL || head->next == NULL) return head; struct ListNode* temp = head->next; head->next = swapPairs(temp->next); temp->next = head; return temp; }