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

      

  • 相关阅读:
    python入门19 异常及异常处理 异常捕获
    python入门18 继承和多态
    python入门17 类和对象
    python入门16 递归函数 高阶函数
    接口测试get请求url拼接函数(python)
    python入门15 函数
    ssh tunnel 三种模式
    k8s 容器的生命周期钩子
    对k8s service的一些理解
    windows下使用pyinstaller把python文件打包成exe可执行文件
  • 原文地址:https://www.cnblogs.com/277223178dudu/p/11411841.html
Copyright © 2020-2023  润新知