标签:
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify 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;
}
}
[LeetCode] Swap Nodes in Pairs
标签:
原文地址:http://www.cnblogs.com/orangeme404/p/4759590.html