鏈表_兩兩交換鏈表中的節點
- 一、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;}
};