leetcode--24--两两交换链表中的节点

2020-07-08  本文已影响0人  minningl

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

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例:

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

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

思路:
1、确定边界终止条件,当链表为空或者链表下一个元素为空,则返回当前链表
2、找返回值:返回给上一层递归的值应该是已经交换完成后的子链表。
3、单次执行过程:用一个guard保存head的下一个元素,递归head.next.next交换链表的返回值作为head的next节点,将guard的next节点赋值为 head

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
        
        guard = head.next
        head.next = self.swapPairs(head.next.next)
        guard.next = head
        
        return guard

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) {
        if (head == nullptr || head->next == nullptr) return head;

        auto guard = head->next;
        head->next = swapPairs(head->next->next);
        guard->next = head;
        return guard;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读