给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
给定 1->2->3->4, 你应该返回 2->1->4->3.
方法一:递归法(动态规划)
思路:
【1】对于链表pre->p->other交换结点
【2】变成p->pre->other
【3】再对other进行翻转。
若other为NULL说明不用再翻转。若other->next为空,说明只剩下一个结点,pre->next直接指向该结点。
ListNode* dpSwap(ListNode* pre, ListNode* p) {
ListNode* other = p->next;
p->next = pre;
if (other == NULL) { //other结点为空说明结点个数为偶数
pre->next = NULL;
}
else if (other->next == NULL) { //other->next为空说明结点个数为奇数
pre->next = other;
}
else {
pre->next = dpSwap(other, other->next);
}
return p;
}
ListNode* swapPairs(ListNode* head) {
//链表为空或只有一个元素直接返回
if (head == NULL || head->next == NULL)
return head;
return dpSwap(head, head->next);
}