Leetcodes Solutions 24 Swap Nodes in Pairs

匯總

雪之下雪乃:leetcode解題總匯?

zhuanlan.zhihu.com圖標

Given 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

利用指針的指針pp一開始指向頭指針。

循環中的前三行做了如下事情

*pp == a -> b -> (b->next)

*pp == b -> a -> (b->next)

第四行讓pp指向下一對

class Solution {public: ListNode* swapPairs(ListNode* head){ ListNode **pp = &head, *a, *b; while((a = *pp) && (b = a->next)){ a->next = b->next; b->next = a; *pp = b; pp = &(a->next); } return head; }};

推薦閱讀:

九章演算法 | Google 面試題:多餘的連接
浙江大學-數據結構-選講旅遊規劃-8.3.2
浙江大學-數據結構-簡單排序-9.1.3
浙江大學-數據結構-選講Complete Binary Search Tree-7.3.3
八、排序 | 數據結構

TAG:編程 | 演算法 | 數據結構 |