leetcode 24

时间:2023-03-10 08:46:24
leetcode 24

leetcode 24

链表操作的,要注意标记头结点和边界问题。

代码如下:

 ListNode *swapPairs(ListNode *head) {
if(head==NULL||head->next==NULL)
return head;
ListNode* p=head;
ListNode* q=head->next;
ListNode* x=head->next->next;
ListNode* t=NULL;
head=q;
while(p!=NULL&&q!=NULL){
q->next=p;
p->next=NULL;
if(t!=NULL)
t->next=q;
t=p; p=x;
if(x!=NULL)
q=x->next;
if(q!=NULL)
x=q->next; }
if(p!=NULL)
t->next=p;
return head;
}

更加巧妙的解法,直接对链表中节点的val进行交换,不用操作链表;

代码如下:

 /**
* 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) {
int n;
ListNode* node = head;
while (head != NULL && head->next != NULL) {
n = head->val;
head->val = head->next->val;
head->next->val = n;
head = head->next->next;
}
return node;
}
};