给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 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; }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/604730.html