算法描述
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1->2->3->4
, you should return the list as2->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.
题目来自此处
解法:
先排除无结点和单个结点的情况~return head;
再在循环扫描链表时进行如下处理:
把本来
head->next_node->temp
的改写成next_node->head->temp_next
。对其中temp_next的存在性进行分类讨论,完毕~
ListNode* swapPairs(ListNode* head) {
if (head == NULL||head->next == NULL) return head;
ListNode *new_head = head->next;
while (head != NULL){
ListNode* next_node = head->next;
ListNode* temp = next_node->next;
next_node->next = head;
if (temp!=NULL&&temp->next!=NULL)
head->next = temp->next;
else if(temp!=NULL&&temp->next==NULL){
head->next = temp;
break;
}
else{
head->next = NULL;
break;
}
head = temp;
}
return new_head;
}
算法的时间复杂度应该是
O(n)
。
最后分类讨论搞得有点复杂 ‘(>﹏<)′
最短的写法是递归,然而不擅长写。。