当前位置: 移动技术网 > IT编程>开发语言>C/C++ > #leetcode刷题之路24-两两交换链表中的节点

#leetcode刷题之路24-两两交换链表中的节点

2019年03月20日  | 移动技术网IT编程  | 我要评论

电脑桌面背景,eset_vc52_autoid,江西省考试网

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

示例:
给定 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;
}

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网