本文為senlie原創,轉載請保留此地址:http://blog.csdn.net/zhengsenlie
Swap Nodes in Pairs
Total Accepted: 12511 Total Submissions: 39302Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
題意:交換給定連結串列中的相鄰節點,但不能夠改變連結串列裡的值
如1->2->3->4交換後為2->1->4->3
思路:
按題意中的掃描去改變每兩個相鄰節點的next指標的指向就可以。
小技巧:
由於處理每兩個相鄰節點的時候,須要一個指標記錄它們前一個節點,而頭節點前面沒有節點,
所以可設定一個dummy節點指向頭指標,這樣開頭的兩個節點的處理方式跟其他的相鄰節點的處理方式就一樣了
複雜度:時間O(n),空間O(1)
/**
* 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) return NULL;
ListNode *dummy = new ListNode(0); dummy->next = head;
ListNode *pre = dummy, *cur = head, *next = head->next;
while(cur && next){
ListNode *temp = next->next;
pre->next = next;
cur->next = next->next;
next->next = cur;
pre = cur;
cur = temp;
next = temp==NULL ? NULL : temp->next;
}
return dummy->next;
}