[LeetCode] Swap Nodes in Pairs

王朝学院·作者佚名  2016-05-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

[LeetCode] Swap Nodes in PairsGiven a linked list, swap every two adjacent nodes and return its head.

For example,Given1->2->3->4, you should return the list as2->1->4->3.

Your algorithm should use only constant space. You maynotmodify the values in the list, only nodes itself can be changed.

这道题难度不大。根据提供的example我们就可以看出这个swap是按照什么顺序来的。就是相邻的两个交换,然后接着下面相邻的两个这样。

那么只要确定head!=null和head.next!=null就可以成功交换值了。if statement这里主要就是判断是否有null出现。

如果到了末尾出现了null的话,PRe/curr也只能变成null了。

理清了思路就很好写了。

代码如下。~

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode swapPairs(ListNode head) { if(head==null||head.next==null){ return head; } ListNode curr=head.next; ListNode pre=head; while(pre!=null&&curr!=null){ int temp=curr.val; curr.val=pre.val; pre.val=temp; if(curr.next==null){ curr=null; pre=null; }else{ pre=curr.next; curr=curr.next.next; } } return head; }}

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航