码迷,mamicode.com
首页 > 其他好文 > 详细

Swap Nodes in Pairs--LeetCode

时间:2015-04-13 12:58:22      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   c++   

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.

思路:将链表拆分,然后再合并

List *swapPairs(List *head) {
    if(head == NULL || head->next == NULL)
     return head;
    List* ji=head;
    List* ou = head->next;
    List* temp1,*temp2;
    List* l1= head;
    List* l2 = head->next;
    temp1 = l2->next;
    while(temp1 != NULL)
    {
      temp2 = temp1->next;
      l1->next = temp1;
      l2->next = temp2;
      l1 = temp1;
      l2 = temp2;
      if(l2 !=NULL)
      temp1 = l2->next;
      else
      temp1 = NULL;
    }
    if(l1 != NULL)
    l1->next =NULL;
    if(l2 != NULL)
    l2->next = NULL;
    temp1 = ou;
    while(temp1 != NULL&&temp1->next != NULL)
    { 
       temp2 = ji->next;
       ji->next = temp1->next;
       temp1->next = ji;
       temp1 = ji->next;
       ji = temp2;         
    }
    temp1->next = ji;
    return ou;
} 


Swap Nodes in Pairs--LeetCode

标签:leetcode   算法   c++   

原文地址:http://blog.csdn.net/yusiguyuan/article/details/45022871

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!