【LeetCode24】. Swap Nodes in Pairs Add to List

来源:互联网 发布:数据统计管理制度pdf 编辑:程序博客网 时间:2024/05/06 18:00
/*****************************************LeetCode24. Swap Nodes in Pairs Add to ListDescription  Submission  SolutionsTotal Accepted: 149955Total Submissions: 400577Difficulty: MediumContributors: AdminGiven 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.**************************************/ListNode* swapPairs(ListNode* head){      if (head == NULL||head->next == NULL )return head;ListNode preHead(0);preHead.next = head; ListNode *pre = &preHead;ListNode *cur = pre->next;ListNode *end  = cur->next->next; while (cur!=NULL && cur->next!=NULL){pre->next = cur->next;cur->next = cur->next->next;pre->next->next = cur; pre = cur;cur = cur->next;} return  preHead.next; }
0 0