- 轉載請註明作者和出處:http://blog.csdn.net/u011475210
- 代碼地址:https://github.com/WordZzzz/Note/tree/master/LeetCode
- 刷題平臺:https://www.nowcoder.com/ta/leetcode
- 題 庫:Leetcode經典編程題
- 編 者:WordZzzz
題目描述
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1->2->3->4, you should return the list as2->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.
解題思路
通過這麼多次的編程練習,鏈表的順序交換我相信大家早已輕車熟路。本題中,我們先寫一個交換相鄰結點的函數swap,此函數交換輸入的兩個相鄰鏈表結點之後,返回新的第一結點。然後我們開始考慮主函數,同樣的新建一個指向頭結點的指針(只要頭結點有可能被替換,我們既需要這麼做),然後遍歷整個鏈表調用交換函數swap即可。
C++版代碼實現
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *swap(ListNode *slow, ListNode *fast){
slow->next = fast->next;
fast->next = slow;
return fast;
}
ListNode *swapPairs(ListNode *head) {
if(head == NULL || head->next == NULL)
return head;
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *cur = dummy;
for(;cur->next != NULL && cur->next->next != NULL; cur = cur->next->next)
cur->next = swap(cur->next, cur->next->next);
return dummy->next;
}
};
系列教程持續發佈中,歡迎訂閱、關注、收藏、評論、點贊哦~~( ̄▽ ̄~)~
完的汪(∪。∪)。。。zzz