设为首页 加入收藏

TOP

#leetcode刷题之路24-两两交换链表中的节点
2019-03-19 12:07:49 】 浏览:68
Tags:#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;
}

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C++构造函数及成员变量 下一篇#leetcode刷题之路23-合并K个排序..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目