[LeetCode]24. Swap Nodes in Pairs
2016-08-26 22:11
441 查看
Given a linked list, swap every two adjacent nodes and return its head.For example,
Given
给定链表,每两个节点为一组,交换相应节点。
解题:1)如果链表为空或者链表只有一个节点,则直接返回链表
2)取出相邻两节点A,B。并把list往后移动两次。3)其实交换两节点实质就是交换两节点的val值,故进行值交换即可。
说明:1)list != NULL检查是防止出现list为NULL时,此时执行list->next会出现段错误。2)list->next != NULL是说明交换的两个节点存在。
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.
给定链表,每两个节点为一组,交换相应节点。
解题:1)如果链表为空或者链表只有一个节点,则直接返回链表
2)取出相邻两节点A,B。并把list往后移动两次。3)其实交换两节点实质就是交换两节点的val值,故进行值交换即可。
说明:1)list != NULL检查是防止出现list为NULL时,此时执行list->next会出现段错误。2)list->next != NULL是说明交换的两个节点存在。
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* swapPairs(struct ListNode* head) { if ( head == NULL || head->next == NULL ) { return head; } struct ListNode *list = head; struct ListNode *swapA = NULL; struct ListNode *swapB = NULL; while ( list != NULL && list->next != NULL ) { swapA = list; swapB = list->next; list = list->next->next; int val = 0; val = swapA->val; swapA->val = swapB->val; swapB->val = val; } return head; }
相关文章推荐
- leetcode 24 Swap Nodes in Pairs
- LeetCode 24.Swap Nodes in Pairs
- Java [leetcode 24]Swap Nodes in Pairs
- Leetcode_24_Swap Nodes in Pairs
- leetcode 24 -- Swap Nodes in Pairs
- [LeetCode]24 Swap Nodes in Pairs
- LeetCode 24 Swap Nodes in Pairs (C,C++,Java,Python)
- Leetcode 24 Swap Nodes in Pairs
- LeetCode 24:Swap Nodes in Pairs
- leetcode_24_Swap Nodes in Pairs
- leetcode 24 Swap Nodes in Pairs
- [leetcode 24]Swap Nodes in Pairs
- Swap Nodes in Pairs - LeetCode 24
- LeetCode24之SwapNodesInPairs的Java 题解
- [Leetcode 22] 24 Swap Nodes in Pairs
- [Leetcode] 24. Swap Nodes in Pairs
- [leetcode 24] Swap Nodes in Pairs
- LeetCode 24 - Swap Nodes in Pairs
- leetcode-24 Swap Nodes in Pairs
- LeetCode_24---Swap Nodes in Pairs