451. Swap Nodes in Pairs

ListNode * swapPairs(ListNode * head) { // write your code here //要用dummy, 要打断三个link,也就重建三个link。dummy->1->2->3,变成dummy -> 2->1->3 if(head == NULL || head->next == NULL){ return head; } ListNode *dummy = new ListNode(0); dummy->next = head; ListNode *pre = dummy; while(head != NULL && head->next != NULL){ ListNode *temp = head->next->next; head->next->next = head; //重建第一个link pre->next = head->next; //重建第二个link head->next = temp; //重建第三个link pre = head;//更新,准备下一次的重建 head = temp; } return dummy->next; }

Comments

Popular posts from this blog

1427. Split Array into Fibonacci Sequence

Amazon OA 763. Partition Labels

05/25 周一