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     }
相关文章
相关标签/搜索