24. 两两交换链表中的节点

24. 两两交换链表中的节点

1、题目描述

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

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

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

2、java题解

    public static ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) return head;

        //伪造出头来
        ListNode headIndex = new ListNode(-1);
        headIndex.next = head;

        //头指针
        ListNode p = headIndex.next;

        ListNode p0 = headIndex;

        while (p != null && p.next != null) {
            //缓存下一个结点
            ListNode saveNode = p.next;
            p.next = saveNode.next;
            saveNode.next = p;
            p0.next = saveNode;

            p = p.next;
            p0 = p0.next.next;
        }

        return headIndex.next;
    }

测试结果:

3、C语言题解

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

    //伪造出头来
    struct ListNode* headIndex = (struct ListNode*)malloc(sizeof(struct ListNode));
    headIndex->val = -1;
    headIndex->next = head;

    //头指针
    struct ListNode* p = headIndex->next;

    struct ListNode* p0 = headIndex;

    while (p != NULL && p->next != NULL) {
        //缓存下一个结点
        struct ListNode* saveNode = p->next;
        p->next = saveNode->next;
        saveNode->next = p;
        p0->next = saveNode;

        p = p->next;
        p0 = p0->next->next;
    }

    return headIndex->next;
}

测试结果:

posted @ 2020-03-02 22:14  孤傲的咸鱼  阅读(216)  评论(0编辑  收藏  举报