zoukankan      html  css  js  c++  java
  • #leetcode刷题之路24-两两交换链表中的节点

    给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
    你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

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

    #include <iostream>
    using namespace std;
    struct ListNode {
        int val;
        ListNode *next;
        ListNode(int x) : val(x), next(NULL) {}
    };
    ListNode* createlist(int n)
    {
        if (n == 0) return nullptr;
        ListNode *head = (ListNode*)malloc(sizeof(ListNode));
        cin >> head->val;
        ListNode *pre = head;
        for (int i = 0; i < n - 1; i++)
        {
            ListNode *p = (ListNode*)malloc(sizeof(ListNode));
            cin >> p->val;
            pre->next = p;
            pre = pre->next;
        }
        pre->next = nullptr;
        return head;
    }
    ListNode* swapPairs(ListNode* head) {
        ListNode* temp = head;
        ListNode* p=head;
        ListNode* q=head;
        if (head == nullptr || head->next == nullptr)
        {
            return  head;
        }
        else if (temp == head)
        {
            p = head->next;
            temp->next = p->next;
            p->next = temp;
            head = p;//head永远是head
            p = head->next;
    
        }
        while (p->next != nullptr&&p->next->next != nullptr)
        {
            temp = p->next->next->next;
            q = p->next;
            p->next = q->next;
            p->next->next = q;
            q->next = temp;
            p = q;
        }
        return head;
    }
    int main() {
        ListNode* head = createlist(4);
        ListNode *ans = swapPairs(head);
        while (ans != nullptr)
        {
            cout << ans->val << endl;
            ans = ans->next;
        }
        return 0;
    }

  • 相关阅读:
    ubuntu18.04更新源
    机器学习网址
    ubuntu18.04下安装Anaconda及numpy、matplotlib
    google云使用记录
    tensorflow省钱方案-ml-engine
    Angular 创建项目
    Angular 环境搭建
    android APP国际化一键切换实现
    android 上下滑动标题栏和状态栏改变颜色实现
    android滑动标题栏渐变实现
  • 原文地址:https://www.cnblogs.com/biat/p/10556854.html
Copyright © 2011-2022 走看看