1. 程式人生 > >LeetCode 24 — Swap Nodes in Pairs(兩兩交換連結串列中的節點)

LeetCode 24 — Swap Nodes in Pairs(兩兩交換連結串列中的節點)

Given a linked list, swap every two adjacent nodes and return its head.

Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
Your algorithm should use only constant extra space.
You may not modify the values in the list’s nodes, only nodes itself may be changed.

翻譯

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

示例:
給定 1->2->3->4, 你應該返回 2->1->4->3.
說明:
你的演算法只能使用常數的額外空間。
你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。

分析
使用三個額外指標。兩個指向需要交換的兩個節點,一個指向指向這兩個節點的前一節點,用來標記這兩個節點。

c++實現

/**
 * 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* pre; ListNode* p = head; ListNode* q ; if(!p) return NULL; if(!p->next) return head; q = p->next; pre = q; head = pre; p->
next = q->next; q->next = p; pre = pre->next; while(1){ p = p->next; if(!p) break; q = p->next; if(!q) break; p->next = q->next; q->next = p; pre->next = q; pre = pre->next->next; } return head; } };