Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
如题所示:
使用递归的方式:请注意递归是一种贪心的算法,旨在找出所有的问题的解决方案。
此题目我们用分治的算法:首先解决的是1->2 如果变成2->1
struct ListNode* swapPairs(struct ListNode* head){ if(head == NULL ) return NULL; struct ListNode* after = head->next; if(after == NULL) return head; head->next = swapPairs(after->next); after->next = head; return after; }
如程序所示:
我们首先规定 如果头指针是空 则返回空。
如果不为空 我们找到头指针的下一个节点
如果下一个节点是空的 我们只返回头节点。
头结点的next 需要和下一次互换之后的结果向连接
头指针的下一个节点连到头指针上面
在此处递归的做法是把分治的思想。。