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.
ListNode *swapPairs(ListNode *head) {
//交换临近节点,不需要额外空间,不能修改节点中的值
ListNode *headL = NULL, *first = NULL, *second = NULL, *next = NULL, *pre = NULL;
//确定头结点
if (head)
headL = first = head;
if (head && head -> next)
headL = second = head -> next;
while (first && second)
{
next = second -> next;
if (pre)
pre -> next = second;
second -> next = first;
first -> next = next;
pre = first;
first = next;
if (first)
second = first -> next;
}
return headL;
}