RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
[LeetCode]24.SwapNodesinPairs

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.SwapNodesinPairs
文章位置:http://scyingshan.cn/article/ihggoj.html