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

LeetCode(24): Swap Nodes in Pairs

时间:2016-01-15 23:09:47      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

Swap Nodes in Pairs: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.

题意:交换一个链表中相邻的两个元素,不能只交换结点元素值,要进行结点的操作。

思路:使用3个指针,分别记录当前指针,当前指针的前驱,当前指针的后继,然后进行交换操作。

代码:

public ListNode swapPairs(ListNode head) {
          if(head==null) return head;
          ListNode pPrePre = null;
          ListNode pPre = null;
          ListNode p = head;
          while(p!=null&&p.next!=null){
              pPre = p;
              p = p.next;
              ListNode pNext = p.next;
              if(pPre==head) head=p;
              if(pPrePre!=null) pPrePre.next = p;
              p.next = pPre;
              pPre.next = pNext;
              pPrePre = pPre;
              p=pNext;
          }
          return head;
    }

LeetCode(24): Swap Nodes in Pairs

标签:

原文地址:http://www.cnblogs.com/Lewisr/p/5134482.html

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