#Leetcode# 24. Swap Nodes in Pairs

https://leetcode.com/problems/swap-nodes-in-pairs/

 

Given a linked list, swap every two adjacent nodes and return its head.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

Note:

  • Your algorithm should use only constant extra space.
  • You may not modify the values in the list's nodes, only nodes itself may be changed.

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode *dummy = new ListNode(-1);
        ListNode *pre = dummy;
        dummy -> next = head;
        while(pre -> next && pre -> next -> next) {
            ListNode *t = pre -> next ->next;
            pre -> next -> next = t -> next;
            t -> next = pre -> next;
            pre ->next = t;
            pre = t -> next;
        }
        return dummy -> next;
    }
};

  链表 画图跑一遍就懂啦

posted @ 2019-01-19 12:58  丧心病狂工科女  阅读(136)  评论(0编辑  收藏  举报