24. 两两交换链表中的节点
24. 两两交换链表中的节点 - 力扣(LeetCode)
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
思路
这道题目正常模拟就可以了。
建议使用虚拟头结点,这样会方便很多,要不然每次针对头结点(没有前一个指针指向头结点),还要单独处理。
做题时候记得先画图,按照图中指针指向的链路写代码就行。使用虚拟头节点的话,这个过程简单很多。注意一下,在交换完一次节点后,需要把虚拟头节点向后移动!一定要移动!
以下是c++实现代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode* pre = new ListNode; if (pre == nullptr) { return pre; } pre->next = head; ListNode* cur = pre; while (cur->next && cur->next->next){ ListNode* first = cur->next; ListNode* third = cur->next->next->next; cur->next = cur->next->next; cur->next->next = first; cur->next->next->next = third; cur = cur->next->next; } head = pre->next; return head; } };
|
c语言实现代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
struct ListNode* swapPairs(struct ListNode* head) { typedef struct ListNode ListNode; ListNode* pre = (ListNode*)malloc(sizeof(ListNode)); if (pre == NULL) { return pre; } pre->next = head; ListNode* cur = pre; while ((cur->next)&& cur->next->next) { ListNode* temp1 = cur->next; ListNode* temp = cur->next->next->next; cur->next = cur->next->next; cur->next->next = temp1; temp1->next = temp; cur = cur->next->next; } head = pre->next; return head; }
|