#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; }