您的位置:首页 > Web前端 > Node.js

[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->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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Code Leet