首页 > 编程语言 > 详细

LeetCode 24. Swap Nodes in Pairs 成对交换节点 C++

时间:2019-04-01 22:07:28      阅读:140      评论:0      收藏:0      [点我收藏+]

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.

奇数位和偶数位互换,若是奇数个,不用管最后一个

解法一:(C++)

 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++)

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     }

 

LeetCode 24. Swap Nodes in Pairs 成对交换节点 C++

原文:https://www.cnblogs.com/hhhhan1025/p/10639087.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!