Given 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.
這道題難度不大。根據(jù)提供的example我們就可以看出這個swap是按照什么順序來的。就是相鄰的兩個交換,然后接著下面相鄰的兩個這樣。
那么只要確定head!=null和head.next!=null就可以成功交換值了。if statement這里主要就是判斷是否有null出現(xiàn)。
如果到了末尾出現(xiàn)了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; }}
|
新聞熱點
疑難解答