LeetCode(24): Swap Nodes in Pairs

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;
    }
posted @ 2016-01-15 21:06  Lewisr  阅读(129)  评论(0编辑  收藏  举报