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.
1:链表为NULL或者链表只有一个节点;2:首先交换头两个节点,确定头节点和尾节点;3:循环交换后两个节点;4当末尾节点个数不大于1的时候,直接添加到当前链表的尾部。
ListNode* swapPairs(ListNode* head)
{
if(head == NULL || head->next == NULL)
return head;
ListNode* temp = head->next;
head->next = temp->next;
temp->next = head;
head = temp;
ListNode* index = head->next;
temp = index->next;
while(temp && temp->next)
{
index->next = temp->next;
index = index->next;
temp->next = index->next;
index->next = temp;
index = index->next;
temp = index->next;
}
index->next = temp;
return head;
}