标签:
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.
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; } };
http://www.waitingfy.com/archives/1583
标签:
原文地址:http://blog.csdn.net/fox64194167/article/details/44086999