/***************************************** LeetCode24. Swap Nodes in Pairs Add to List Description Submission Solutions Total Accepted: 149955 Total Submissions: 400577 Difficulty: Medium Contributors: Admin 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. **************************************/ ListNode* swapPairs(ListNode* head) { if (head == NULL||head->next == NULL ) return head; ListNode preHead(0); preHead.next = head; ListNode *pre = &preHead; ListNode *cur = pre->next; ListNode *end = cur->next->next; while (cur!=NULL && cur->next!=NULL) { pre->next = cur->next; cur->next = cur->next->next; pre->next->next = cur; pre = cur; cur = cur->next; } return preHead.next; }
【LeetCode24】. Swap Nodes in Pairs Add to List

最新推荐文章于 2024-07-26 10:48:09 发布
