20220924 - 24. Swap Nodes in Pairs 两两交换链表中的节点

98 阅读1分钟

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

Example 1:

Input: head = [1,2,3,4]
Output: [2,1,4,3]

Example 2:

Input: head = []
Output: []

Example 3:

Input: head = [1]
Output: [1]

  Constraints:

  • The number of nodes in the list is in the range [0, 100].
  • 0 <= Node.val <= 100

Solution

自己想的办法:用三个指针去操作,还要特判,没有加头节点

/**
 * 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 *p, *q, *r;
    p = head;
    q = p->next;
    r = q->next;
    head = q;
    while (r) {
        q->next = p;
        q = r->next;
        if (q) {
            p->next = q;
            p = r;
            r = q->next;
        } else {
            p->next = r;
            r = NULL;
        }
    }
    if (q) {
        q->next = p;
        p->next = r;
    }
    return head;
}

题解用的方法:加头节点

如果 tmp 的后面没有节点或者只有一个节点,则没有更多的节点需要交换,因此结束交换。否则,获得 tmp 后面的两个节点 p 和 q,通过更新节点的指针关系实现两两交换节点。

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

struct ListNode* swapPairs(struct ListNode* head){
    struct ListNode *Head = (struct ListNode*)malloc(sizeof(struct ListNode));
    Head->next = head;
    struct ListNode *tmp, *p, *q;
    tmp = Head;
    while (tmp->next && tmp->next->next) {
        p = tmp->next;
        q = tmp->next->next;
        tmp->next = q;
        p->next = q->next;
        q->next = p;
        tmp = p;
    }
    return Head->next;
}

题目链接: 24. 两两交换链表中的节点 - 力扣(LeetCode)