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. 

代码:

class Solution {

public:

  ListNode *swapPairs(ListNode *head) {

    if (head == NULL || head->next == NULL) {

      return head;

    }

    ListNode dummy(-1);

    dummy.next = head;

    for (ListNode *prev = &dummy, *cur = prev->next, *next = cur->next; next; prev = cur, cur = cur->next, next = cur ? cur->next : NULL) {

      prev->next = next;

      cur->next = next->next;

      next->next = cur;

    }

    return dummy.next;

  }

};

 

下面这种写法更简单,但是题目规定了允许这么做

class Solution {

public:

  ListNode *swapPairs(ListNode *head) {

    ListNode *p = head;

    while (p && p->next) {

      swap(p->val, p->next->val);

      p = p->next->next;

    }

    return head;

  }

};

posted @ 2017-12-15 10:09  飘舞的雪  阅读(93)  评论(0编辑  收藏  举报