leetcode: Swap Nodes in Pairs
2013-10-28 22:34
435 查看
http://oj.leetcode.com/problems/swap-nodes-in-pairs/
思路:
每次读两个节点插入新链表,因为是指针操作,不占用额外空间。最后需要把tail指针的next设为NULL。例如链表为p1->p2->p3->p4的情况,如果最后不修改p3->next,那么就会出现一个环:p2->p1->p4->p3->p4->...
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.
思路:
每次读两个节点插入新链表,因为是指针操作,不占用额外空间。最后需要把tail指针的next设为NULL。例如链表为p1->p2->p3->p4的情况,如果最后不修改p3->next,那么就会出现一个环:p2->p1->p4->p3->p4->...
class Solution { public: void insertTwoNodes(ListNode *p1, ListNode *p2, ListNode *&head, ListNode *&tail) { if (NULL == head) { head = tail = p2; } else { if (p2 != NULL) { tail->next = p2; tail = p2; } } if (NULL == head) { head = tail = p1; } else { tail->next = p1; tail = p1; } } ListNode *swapPairs(ListNode *head) { ListNode *swapped_head = NULL, *swapped_tail = NULL; while (head != NULL) { ListNode *p1 = NULL, *p2 = NULL; p1 = head; head = head->next; if (head != NULL) { p2 = head; head = head->next; } insertTwoNodes(p1, p2, swapped_head, swapped_tail); } if (NULL != swapped_tail) { swapped_tail->next = NULL; } return swapped_head; } };
相关文章推荐
- LeetCode_24---Swap Nodes in Pairs
- LeetCode—Swap Nodes in Pairs
- LeetCode 23. Swap Nodes in Pairs
- 【LeetCode】Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs
- leetcode[24]Swap Nodes in Pairs
- Leetcode: Swap Nodes in Pairs
- LeetCode 24:Swap Nodes in Pairs
- LeetCode Swap Nodes in Pairs
- 【LeetCode】Swap Nodes in Pairs && Reverse Nodes in k-Group
- [Leetcode] Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs
- 【C++】【LeetCode】24. Swap Nodes in Pairs
- leetcode - Swap Nodes in Pairs
- LeetCode - Swap Nodes in Pairs
- LeetCode之Swap Nodes in Pairs
- LeetCode - 24. Swap Nodes in Pairs
- LeetCode :: Swap Nodes in Pairs [详细分析]
- LeetCode: Swap Nodes in Pairs 解题报告
- Leetcode-24 Swap Nodes in Pairs