24. 两两交换链表中的节点
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
/* 解题思路: 递归和迭代来实现。对于迭代实现,还是需要建立dummy节点, 注意在连接节点的时候,最好画个图 */ #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<vector> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* CreateListNode(int arr[], int n) { ListNode* head; head = new ListNode(arr[0]); ListNode* cur; cur = head; for (int i = 1; i < n; i++) { cur->next = new ListNode(arr[i]); cur = cur->next; } return head; } class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode *dummy = new ListNode(-1), *pre = dummy; dummy->next = head; while (pre->next && pre->next->next) { ListNode *t = pre->next->next; pre->next->next = t->next; t->next = pre->next; pre->next = t; pre = t->next; } return dummy->next; } }; int main() { int n; cin >> n; int i; int a[100]; for (i = 0; i < n; i++) { scanf("%d", &a[i]); } ListNode* head = CreateListNode(a, n); ListNode* result = Solution().swapPairs(head); while (result != NULL) { printf("%d ", result->val); result = result->next; } system("pause"); return 0; }