Description
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->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.
Example
/**
* 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 p = head; //当前节点k
ListNode q = head.next; //下一节点k+1
ListNode r = null; //记录上一节点k-1
head = q;
while(p != null && q != null) {
p.next = q.next; //交换next
q.next = p;
if(r != null) r.next = q; //更新上一节点的next
r = p; //更新节点
p = p.next;
if(p != null) q = p.next;
}
return head;
}
}