LeetCode Swap Nodes in Pairs
來源:程序員人生 發布時間:2015-04-07 08:06:28 閱讀次數:2755次
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
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈