程序员人生 网站导航

LeetCode Swap Nodes in Pairs

栏目:综合技术时间:2015-04-07 08:06:28

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


------分隔线----------------------------
------分隔线----------------------------

最新技术推荐