Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list's nodes, only nodes itself may be changed.
/**Java主要注意边界问题就好了
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode p1=head;
ListNode p2=head.next;
while(p2!=null){
int t=p2.val;
p2.val=p1.val;
p1.val=t;
if(p1.next!=null&&p1.next.next!=null)
{p1=p1.next.next;
}else
break;
if(p2.next!=null&&p2.next.next!=null)
{p2=p2.next.next;}
else
break;
}
return head;
}
}
递归方法
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode p1=head.next;
ListNode p2=p1.next;
p1.next=head;
head.next=swapPairs(p2);
return p1;
}
}