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.
分析:题目给出一个链表,要求每两个节点进行交换并输出。
思路如下:
Java代码如下:
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode current1=head;
ListNode current2=head.next;
ListNode result=head.next;
while(current2.next!=null&¤t2.next.next!=null){
ListNode mynext=current2.next;
current1.next=mynext.next;
current2.next=current1;
current1=mynext;
current2=mynext.next;
}
current1.next=current2.next;
current2.next=current1;
return result;
}