• 【LeetCode】24. 两两交换链表中的节点


    【题目描述】

    给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

    你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

    示例:

    给定 1->2->3->4, 你应该返回 2->1->4->3.

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs

    【解题思路】

    增加一个哑节点dummy,dummy->next指向head;

    保持后续操作的一致性;

    【提交代码】

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     struct ListNode *next;
     6  * };
     7  */
     8 struct ListNode* swapPairs(struct ListNode* head){
     9     struct ListNode *dummy;
    10     struct ListNode *pre;
    11     struct ListNode *cur;
    12     struct ListNode *next;
    13     struct ListNode *tmp;
    14 
    15     dummy = (struct ListNode *)malloc(sizeof(struct ListNode));
    16     dummy->next = head;
    17 
    18     pre = dummy;
    19     cur = head;
    20 
    21     while( cur != NULL && cur->next != NULL )
    22     {
    23         next = cur->next;
    24 
    25         tmp = next->next;
    26 
    27         pre->next = next;
    28         next->next = cur;
    29         cur->next = tmp;
    30 
    31         pre = cur;
    32         cur = tmp;
    33         //pre = pre->next->next;
    34     }
    35 
    36     return dummy->next;
    37 }
  • 相关阅读:
    springboot、监听器
    springboot、拦截器
    Thymeleaf模板引擎
    springboot-banner.txt
    springboot,swagger2
    springboot 热部署
    判断是否为微信环境下打开的网页
    后台接收json数据
    ios 面试题
    iOS 适配问题
  • 原文地址:https://www.cnblogs.com/utank/p/13262162.html
Copyright © 2020-2023  润新知