LeetCode Swap Nodes in Pairs
来源:程序员人生 发布时间:2015-04-07 08:06:28 阅读次数:2583次
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.解决方案
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
ListNode* returnNode = head;
ListNode* preNode = NULL;
while(head != NULL && head->next != NULL){
ListNode* firstNode = head;
ListNode* secondNode = head->next;
if(preNode != NULL){//first node
preNode->next = secondNode;
}else{
if(secondNode != NULL){
returnNode = secondNode;
}
}
firstNode->next = secondNode->next;
secondNode->next = firstNode;
preNode = head;
head = head->next;
}
return returnNode;
}
};
思路:这题还是比较简单的。while循环,交换两个指针而已。但要注意细节和返回的值。
http://www.waitingfy.com/archives/1583
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠