Try   HackMD

Leetcode 24. Swap Nodes in Pairs (C語言)

  • 題目
    Given a linked list, swap every two adjacent nodes and return its head.

    You may not modify the values in the list's nodes, only nodes itself may be changed.

  • 範例

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.
struct ListNode* swapPairs(struct ListNode* head){ if(!head||!head->next)return head; if(!head->next->next){ struct ListNode *ptr=head; head=ptr->next; ptr->next->next=ptr; ptr->next=NULL; return head; } struct ListNode *ptr=head,*ptr2=head->next->next; head=ptr->next; ptr->next=ptr2; head->next=ptr; while(ptr2->next){ ptr2=ptr2->next; ptr->next->next=ptr2->next; ptr2->next=ptr->next; ptr->next=ptr2; ptr=ptr2->next; if(ptr->next){ ptr2=ptr->next; }else{ return head; } } return head; }

思路: 假設 a->b->c->d 其中b,c為要swap的偶數對 則宣告兩指標 ptr ptr2指向a&c

 a->b->c->d
 ^     ^
ptr    ptr2

要做事情有3

  1. 將b改指向d
 a->b->
 ^      d    
ptr c->
    ^
   ptr2
  1. 將c改指向b
ptr
 a->
     b->d
 c->
ptr2
  1. 將a改指向c
ptr
 a->c->b->d
   ptr2 

至此bc完成swap且ad正確接上
最後ptr與ptr2位置往前循環做1-3步(ptr到b,ptr2到d的下一個)
如果d沒有下一個直接回傳