代码随想录 Day6
24. 两两交换链表中的节点
struct ListNode* swapPairs(struct ListNode* head) { if(head==NULL||head->next==NULL) return head; struct ListNode* p= NULL; struct ListNode *q=NULL; struct ListNode *pre=NULL; p=head; q=head->next; p->next=q->next; q->next=p; head=q; pre=head->next; while(p->next!=NULL) { p=p->next; if(p!=NULL) { q=p->next; if(q!=NULL) {p->next=q->next; q->next=p; pre->next=q; pre=pre->next->next;}} } return head; }笔记:使用暴力解法,
if(q!=NULL), if(p!=NULL) 判断节点是否为空的条件
struct ListNode* p= NULL; 加星号
更简洁的方法:
struct ListNode* swapPairs(struct ListNode* head) { struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode)); dummy->val = 0; dummy->next = head; struct ListNode* pre = dummy; while (pre->next != NULL && pre->next->next != NULL) { struct ListNode* p = pre->next; struct ListNode* q = pre->next->next; pre->next = q; p->next = q->next; q->next = p; pre = p; } struct ListNode* newHead = dummy->next; free(dummy); return newHead; }