24. 两两交换链表中的节点
个人感觉这个不太难,刚开始打算用步进值为2,来搞,但是没有想到链表应该是怎么样的,
原来可以直接用:
1 cur = cur->next->next
学到了,这是我自己写的代码:
1 ListNode* MyLinkedList::swapPairs(ListNode* head) 2 { 3 ListNode* dummyHead = new ListNode(); 4 dummyHead->next = head; 5 auto* cur = dummyHead; 6 7 int idx = 0; 8 while (cur->next != nullptr) 9 { 10 if (idx % 2 == 0 && cur->next->next !=nullptr) 11 { 12 auto* first = cur->next; 13 auto* second = cur->next->next; 14 15 first->next = second->next; 16 second->next = first; 17 cur->next = second; 18 } 19 20 idx++; 21 cur = cur->next; 22 } 23 24 return dummyHead->next; 25 }
标签:24,dummyHead,ListNode,cur,随想录,next,链表,节点 From: https://www.cnblogs.com/smartisn/p/17471275.html