链表_两两交换链表中的节点
- 一、leetcode-24
- 二、题解
- 1.引库
- 2.代码
一、leetcode-24
两两交换链表中的节点
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
输入:head = [1,2,3,4]
输出:[2,1,4,3]
二、题解
1.引库
#include <iostream>#include <cstdio>#include <cstdlib>#include <queue>#include <stack>#include <algorithm>#include <string>#include <map>#include <set>#include <vector>using namespace std;
2.代码
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* swapPairs(ListNode* head) {ListNode *newhead=new ListNode(0);newhead->next=head;ListNode *cur=newhead;while(cur->next!=NULL&&cur->next->next!=NULL){ListNode *tmp1=cur->next,*tmp2=cur->next->next;cur->next=tmp2;tmp1->next=tmp2->next;tmp2->next=tmp1;cur=tmp1;}ListNode *result=newhead->next;delete newhead;return result;}
};