LeetCode 24 - Swap Nodes in Pairs

一、问题描述

Description:

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.

Note:

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

给一个链表,交换每两个相邻的结点,返回新链表。


二、解题报告

解法一:操作值域

直接交换结点的val是最简单的:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == NULL)
            return NULL;
        ListNode* first = head;
        ListNode* second = head->next;
        while(first!=NULL && second!=NULL) {
            int temp = first->val;      // 交换val
            first->val = second->val;
            second->val = temp;
            if(first->next!=NULL)
                first = first->next->next;
            if(second->next!=NULL)
                second = second->next->next;
        }
        return head;
    }
};


解法二:操作结点

题目要求:You may not modify the values in the list, only nodes itself can be changed. 好吧,那就来操作结点吧。

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == NULL)
            return NULL;
        ListNode* first = head;
        ListNode* second = head->next;
        ListNode* p = new ListNode(0);
        head = p;
        while(first!=NULL && second!=NULL) {
            ListNode* temp1 = first;
            ListNode* temp2 = second;
            if(second->next!=NULL)
                second = second->next->next;
            if(first->next!=NULL)
                first = first->next->next;
            p->next = temp2;
            p->next->next = temp1;
            p = p->next->next;
            p->next = NULL;
        }
        if(first!=NULL) {
            p->next = first;
        }
        return head->next;
    }
};

空间复杂度为O(1)





LeetCode答案源代码:https://github.com/SongLee24/LeetCode


转载于:https://www.cnblogs.com/songlee/p/5738042.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值