Bootstrap

Leetcode 24. 两两交换链表中的节点(中等) 递归法与非递归法(迭代法)

题目描述:

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

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

 

示例:

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

来源:力扣(LeetCode)
 

思路:

1、迭代法整个思路是,

     pre,now,nex, nex->next;

     先让pre->next 指向 nex,

     然后让 now指向nex->next;

     接着nex->next 指向now;

     最后更新pre(程序中是 中间变量 p)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode* swapPairs(struct ListNode* head){
    if(head == NULL || head->next == NULL) return head;

    struct ListNode* now;
    struct ListNode* nex;
    struct ListNode* pre = (struct ListNode*)malloc(sizeof(struct ListNode));
    pre->val = 0;
    pre->next = head;
    struct ListNode* p = pre;
    
    while(p->next && p->next->next)
    {
        now = p->next;
        nex = p->next->next;
        p->next = nex;
        now->next = nex->next;
        nex->next = now;
        p = now;
    }
    return pre->next;
}

2、递归法

      每次递归返回的是: 交换完成的子链表(从后向前,递归到最后两个或者一个)
      每次递归调用做的是: 交换head 和 nex,head后面接已经交换完成的子链表,nex后则接的是head
      每次返回的条件:head 为NULL或者 nex 为NULL,即当前节点为空或者此时只剩一个节点,你不用再进行交换

参考的题解:https://leetcode-cn.com/problems/swap-nodes-in-pairs/solution/hua-jie-suan-fa-24-liang-liang-jiao-huan-lian-biao/

递归思想有点难。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode* swapPairs(struct ListNode* head){
    if(head == NULL || head->next == NULL) return head;

    struct ListNode* nex = head->next;
    head->next = swapPairs(nex->next);
    nex->next = head;
    return nex;

}

 

 

;