【Leetcode】24.两两交换链表中的节点C++

在这里插入图片描述
在这里插入图片描述

#include "iostream"

using namespace std;

struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution
{
public:
    void print(ListNode *head)
    {
        ListNode *p = head;
        while (p != NULL)
        {
            cout << p->val << " ";
            p = p->next;
        }
        cout << endl;
    }
    ListNode *swapPairs(ListNode *head)
    {
        if (head == NULL)
        {
            return NULL;
        }
        else if (head->next == NULL)
        {
            return head;
        }

        ListNode *node = new ListNode(0);

        node->next = head;

        ListNode *p = head, *s = head->next;
        ListNode *f=node;

        // 1 2 3 4
        while (true)
        {
            p->next = s->next;
            s->next = p;
            f->next = s;

            f = p;
            p = p->next;

            if(p==NULL)
            {
                break;
            }

            s = p->next;

            if(s==NULL)
            {
                break;
            }
        }

        return node->next;
    }
};

int main(int argc, char const *argv[])
{
    int x;
    ListNode *p, *head;

    cin >> x;
    head = new ListNode(x);
    p = head;
    while (true)
    {
        cin >> x;
        p->next = new ListNode(x);
        p = p->next;
        if (cin.get() == '\n')
            break;
    }

    Solution so;
    head = so.swapPairs(head);

    return 0;
}
发布了103 篇原创文章 · 获赞 128 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44936889/article/details/104088577
今日推荐