首页 > 其他 > 详细

[LeetCode]24. Swap Nodes in Pairs

时间:2016-08-27 00:41:35      阅读:228      评论:0      收藏:0      [点我收藏+]

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;
}


[LeetCode]24. Swap Nodes in Pairs

原文:http://11998200.blog.51cto.com/11988200/1843121

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!