leetcode_24


题目描述

Given a linked list, swap every two adjacent nodes and return its head.

Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.


Note:
Your algorithm should use only constant extra space.
You may not modify the values in the list’s nodes, only nodes itself may be changed.

思路:

定义三个指针分别为p, q, k,先让q指针指向p节点,将两个链表节点交换,p指针指向k节点,如果链表的下一个节点不为空时将三个指针整体后移直到结束
[LeetCode_24] Swap Nodes in Pairs_两两交换链表中的节点

代码:

    /**
     * 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 = head, *q = head->next, *k = head->next->next;
        head = head->next;
        while(1) {
            q->next = p;
            p->next = k;
            //判断k和k的后边是否为空
            if(k && k->next) {
                //整体后移
                p->next = k->next;
            }
            p = k;
            if(p == NULL ||p->next == NULL) break;
            q = p->next;
            k = q->next;
        }
        return head;
    }
    



相关文章:

  • 2021-09-29
  • 2021-12-14
  • 2021-05-18
  • 2021-05-19
  • 2022-12-23
  • 2021-11-11
猜你喜欢
  • 2022-12-23
  • 2021-08-11
  • 2021-09-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-27
相关资源
相似解决方案