温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

[LeetCode]24. Swap Nodes in Pairs

发布时间:2020-10-20 09:30:40 来源:网络 阅读:271 作者:風子余 栏目:编程语言

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


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI