[LeetCode 题解]:Swap Nodes in Pairs
前言
【LeetCode 题解】系列传送门: http://www.cnblogs.com/double-win/category/573499.html
1.题目描述
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.
2. 题意
给定一个链表,请将链表中任意相邻的节点互换,并返回链表的头部
要求:算法必须使用常量空间,并且不能改变节点的值,只能改变节点的位置。
3. 思路
步骤一:删除current->next
步骤二:将tmp插入到current之前
步骤三: 递归调用
注意递归的终止条件:
current!=NULL && current->next!=NULL //剩余的节点大于等于两个
4: 解法
ListNode *swapPairs(ListNode *head){ if(head==NULL || head->next==NULL) return head; ListNode *pre=new ListNode(0); pre->next = head; ListNode *newHead =pre; ListNode *current =head; while(current && current->next){ //删除current->next ListNode *tmp = current->next; current->next = current->next->next; //插入tmp tmp->next = pre->next; pre->next=tmp; //向后递归 pre=current; current=current->next; } return newHead->next; }
作者:Double_Win 出处: http://www.cnblogs.com/double-win/p/3939649.html 声明: 由于本人水平有限,文章在表述和代码方面如有不妥之处,欢迎批评指正~ |