代码随想录算法训练营第四天|24. 两两交换链表中的节点 , 19.删除链表的倒数第N个节点 , 面试题 02.07. 链表相交 , 142.环形链表II

发布时间 2023-06-10 14:53:21作者: 博二爷

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 }