[Leetcode24]两两交换链表中的节点

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

说明:

  • 你的算法只能使用常数的额外空间。
  • 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

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):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None or head.next == None:
            return head
        if head.next :
            begin = ListNode(head.next.val)
            head.next = head.next.next
            begin.next = head
        while head.next :
            if head.next.next :
                temp = ListNode(head.next.val)
                head.next = head.next.next
                temp.next = head.next.next
                head.next.next = temp
                head = temp
            else:
                break
        return begin

            

C++:

C++相对于python来说要注意的是变量的作用域,要在函数作用域里创建一个res作为开头存下来方便后续输出。 

/**
 * 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* res = new ListNode(0);
        if(head == NULL || head->next == NULL) return head;
        if(head->next){
            ListNode* begin = new ListNode(head->next->val);
            head->next = head->next->next;
            begin->next = head;
            res = begin;
        }
        while(head->next){
            if(head->next->next){
                ListNode* temp = new ListNode(head->next->val);
                head->next = head->next->next;
                temp->next = head->next->next;
                head->next->next = temp;
                head = temp;
            }
            else break;
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_40501689/article/details/84402529