leetcode——Swap Nodes in Pairs
思路1:
class Solution { public: // 两个指针,p, q, q指向第二个,preP是p之前 ListNode *swapPairs(ListNode *head) { if(head == NULL) return NULL; auto p = head; auto q = head->next; ListNode preHead(-1); ListNode* preP = &preHead; preP->next = p; ListNode* tmp; while(q){ preP->next = q; tmp = q->next;// 记录q之后,作为下一个p q->next = p; preP = p; if(tmp) p = tmp; else break; q = p->next; } return preHead.next; } };
结果是超时了,后来看了别的答案之后发现是tmp=q->next这句处理的不好,不应该用临时变量,而用p->next = q->next;这样下一个p可以是p->next:
class Solution { public: // 两个指针,p, q, q指向第二个,preP是p之前 ListNode *swapPairs(ListNode *head) { if(head == NULL) return NULL; auto p = head; auto q = head->next; ListNode preHead(-1); ListNode* preP = &preHead; preP->next = p; while(q){ preP->next = q; p->next = q->next;// 记录q之后,作为下一个p q->next = p; preP = p; p = p->next; q = p?p->next:nullptr; } return preHead.next; } };