快乐的LeetCode --- 24. 两两交换链表中的节点

题目描述:

  给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.

解题思路1:
在这里插入图片描述
每次做完一对之后,让p指向当前a的位置

在这里插入图片描述


C++写法:

代码:

/**
 * 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) {
        auto dummy = new ListNode(-1);
        dummy -> next = head;

        for(auto p = dummy; p -> next && p -> next -> next;)
        {
            auto a = p -> next, b = a -> next;
            p -> next = b;
            a -> next = b -> next;
            b -> next = a;
            p = a;
        }
        return dummy -> next;
    }
};

python写法:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def swapPairs(self, head):

        dummy = ListNode(-1)
        dummy.next = head

        p = dummy
        while p.next and p.next.next:
            a = p.next
            b = a.next
            p.next = b
            a.next = b.next
            b.next = a
            p = a

        return dummy.next

题目来源:

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章