LeetCode24. 两两交换链表中的节点 Swap Nodes in Pairs(C语言)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hang404/article/details/85067050

题目描述:

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

示例:

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

说明:

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

题目解答:

方法1:遍历交换

为了保证逻辑简单,排除特殊情况,插入头结点,另外使用三个指针。
运行时间0ms,代码如下。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* swapPairs(struct ListNode* head) {
    struct ListNode* front = (struct ListNode*)malloc(sizeof(struct ListNode));
    front->next = head;
    struct ListNode *t = front, *t1 = NULL, *t2 = NULL;
    while(t && t->next && t->next->next) {
        t1 = t->next;
        t2 = t1->next;
        t->next = t2;
        t1->next = t2->next;
        t2->next = t1;    
        t = t1;
    }
    t = front->next;
    free(front);
    return t;
}

方法2:递归法

但是递归使用了O(N)的空间,非O(1)。应该使用尾递归或者迭代
运行时间0ms,代码如下。

/**
 * 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* temp = head->next;
    head->next = swapPairs(temp->next);
    temp->next = head;
    return temp;
}

猜你喜欢

转载自blog.csdn.net/hang404/article/details/85067050