LeetCode 24. Swap Nodes in Pairs 成對交換節點 C++/Java

Given a linked list, swap every two adjacent nodes and return its head.java

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

Example:spa

Given 1->2->3->4, you should return the list as 2->1->4->3.

奇數位和偶數位互換,如果奇數個,不用管最後一個code

解法一:(C++)blog

 1 ListNode* swapPairs(ListNode* head) {  2         if(!head)  3             return NULL;  4         ListNode* dummy=new ListNode(-1),*cur=dummy;  5         dummy->next=head;  6         while(cur->next&&cur->next->next){  7             ListNode* t=cur->next->next;  8             cur->next->next=t->next;  9             t->next=cur->next; 10             cur->next=t; 11             cur=t->next; 12  } 13         return dummy->next; 14     }

java:遞歸

 1 public ListNode swapPairs(ListNode head) {  2         if(head==null)  3             return null;  4         ListNode dummy=new ListNode(-1),pre=dummy;  5         dummy.next=head;  6         while(pre.next!=null&&pre.next.next!=null){  7             ListNode t=pre.next.next;  8             pre.next.next=t.next;  9             t.next=pre.next; 10             pre.next=t; 11             pre=t.next; 12  } 13         return dummy.next; 14     }

方法二:使用遞歸的方法,遞歸遍歷到末尾兩個,而後交換末尾兩個,依次往前遍歷(C++)it

1 ListNode* swapPairs(ListNode* head) { 2         if(!head||!head->next) 3             return head; 4         ListNode* t=head->next; 5         head->next=swapPairs(head->next->next); 6         t->next=head; 7         return t; 8     }
相關文章
相關標籤/搜索