Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
给定一个链表,依次交换其邻接的两个节点,返回最终结果。
不能通过修改节点的值来实现交换。
一般情况下,链表的题可以通过转化成数组进行求解。假如这里没有条件限制,我们可以:
但是这里规定不能通过修改链表节点的值,所以这里主要考察的就是对指针的操作。
实际的解法是:
while (node->next && node->next->next)
;node 初始化为新声明的头结点;1->2->3->4
:声明头结点后,链表为-1->1->2->3->4
,node初始化指向-1;-1->1->3->4
,同时2也指向3;temp->next = node->next
,/**
* 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) {
if(!head || !head->next) return head;
ListNode *first = new ListNode(-1), *node = first;
first->next = head;
while (node->next && node->next->next){
ListNode *temp = node->next->next;
node->next->next = temp->next;
temp->next = node->next;
node->next = temp;
node = node->next->next;
}
return first->next;
}
};