LeetCode24. 两两交换链表中的节点
题目
分析
利用哑结点方便操作。
head->n1->n2->n3->n4
交换步骤
1. n1指向n3
2. n2指向n1
3. head->next 指向n2
4. head指向n1(n3的前一个结点)
代码
1 class Solution { 2 public: 3 ListNode* swapPairs(ListNode* head) { 4 if(!head || !head->next) return head; //只有一个结点或者空结点 5 ListNode *dummyHead = new ListNode(0); //创造哑节点 6 dummyHead->next = head; 7 head = dummyHead; 8 9 while(head && head->next && head->next->next){ 10 auto n1 = head->next; 11 auto n2 = head->next->next; 12 //head->n1->n2-> ... -> 13 n1->next = n2->next; //先操作n1防止断链 14 n2->next = n1; 15 head->next = n2; 16 head = n1; 17 } 18 return dummyHead->next; 19 } 20 };
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode() : val(0), next(nullptr) {} 7 * ListNode(int x) : val(x), next(nullptr) {} 8 * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 ListNode* swapPairs(ListNode* head) { 14 auto dummy = new ListNode(-1),cur = dummy; 15 dummy->next = head; 16 while(cur->next && cur->next->next){ 17 18 auto p1 = cur->next,p2 = cur->next->next; 19 20 cur->next = p2; 21 p1->next = p2->next; 22 p2->next = p1; 23 24 cur = p1; 25 } 26 return dummy->next; 27 } 28 };
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号