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.
交换相邻两个节点的位置,由于要设置更换头结点,为了避免对头结点的特殊情况进行讨论,加入一个新的头结点,返回时删除新的头结点。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
ListNode p,q,r;
if(head==null )return head;
if(head.next==null)return head;
ListNode newHead=new ListNode(0);
newHead.next=head;
q=newHead;
p=head;
while(p!=null && p.next!=null)
{
r=p.next;
q.next=r;
q=r.next;
r.next=p;
p.next=q;
r=p;
p=q;
q=r;
}
return newHead.next;
}
}