LeetCode 24. Swap Nodes in Pairs

本文介绍了一种链表操作的方法,即将链表中相邻的两个节点进行交换,并提供了详细的实现步骤及C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

24. Swap Nodes in Pairs

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.

题目描述:
给定一个数组链表,将数组链表中的元素两两交换位置。

解题思路:
因为需要将链表元素两两交换,所以在这里我先获取到链表的前2个元素(如果链表元素不少于2)。然后在一个while循环里面,先将当前获取到的两个元素交换,然后再尝试获取下一个元素,

  • 如果后面已经没有元素了,就返回;
  • 如果还存在下一个元素,那么就尝试获取下下个元素;
    • 如果没有,也可以直接返回,因为后面剩下一个元素,已经不能进行交换了;
    • 如果还存在元素,那么就获得了后面的2个元素进行下一步的处理。

代码:

#include <iostream>

using namespace std;

/**
 * Definition for singly-linked list.
 */
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

void PrintList(ListNode* l) {
    if (l == NULL) {
        return;
    }
    ListNode* currentNode = l;
    while (currentNode != NULL) {
        if (currentNode != l) {
            cout << "->" ;
        }
        cout << currentNode->val;
        currentNode = currentNode->next;
    }
    cout << endl;
}

ListNode* Convert2ListNode(string val) {
    if (val == "") {
        return NULL;
    }
    ListNode* l = new ListNode(val[0] - '0');
    ListNode* start = l;
    std::string::iterator it = val.begin() + 1;
    for(; it != val.end(); it++) {
        l->next = new ListNode(*it - '0');
        l = l->next;
    }
    return start;
}


class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head == NULL) {
            return NULL;
        }
        if (head->next ==  NULL) {
            return head;
        }
        ListNode* start = head->next;
        ListNode* node0 = head;
        ListNode* node1 = head->next;
        while(node1) {
            ListNode* temp = node1->next;
            node1->next = node0;
            node0->next = temp;

            if (temp == NULL || temp->next == NULL) break;
            node0->next = temp->next;
            node0 = temp;
            node1 = temp->next;
        }
        return start;
    }
};

int main(int argc, const char * argv[]) {
    Solution sln;
    ListNode* l = Convert2ListNode("1234");
    PrintList(sln.swapPairs(l));
    std::cout << "Hello, World!\n";
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值