0
点赞
收藏
分享

微信扫一扫

Swap Nodes in Pairs 链表交换相邻的节点

野见 2023-02-18 阅读 21


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

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
if(head==NULL||head->next==NULL)
{
return head;
}
int temp;
ListNode *p=head;
while(p&&p->next)
{
temp=p->val;
p->val=p->next->val;
p->next->val=temp;
p=p->next;
p=p->next;
}
return head;
}
};

举报

相关推荐

0 条评论