码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode Swap Nodes in Pairs

时间:2015-04-21 20:36:38      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

我写的代码就不贴了。下面这个是discuss里看的,代码真的好简洁,而且思路清晰,并不影响阅读,学习

 1 public class Solution {
 2   public ListNode swapPairs(ListNode head) {
 3     ListNode start = new ListNode(0); //make head no longer a special case
 4     start.next = head;
 5 
 6     for(ListNode cur = start; cur.next != null && cur.next.next != null; cur = cur.next.next) {
 7       cur.next = swap(cur.next, cur.next.next);        
 8     }
 9     return start.next;
10   }
11   private Listnode swap(ListNode next1, ListNode next2) {
12     next1.next = next2.next;
13     next2.next = next1;
14     return next2;
15   }
16 }

这个代码中最出彩的是swap这个函数的书写,交换完成之后返回需要的指针。

leetcode Swap Nodes in Pairs

标签:

原文地址:http://www.cnblogs.com/chaiwentao/p/4445255.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!