zoukankan      html  css  js  c++  java
  • 【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 }
  • 相关阅读:
    第一次作业
    C语言I博客作业04
    C语言I博客作业05
    c语言l博客作业02
    C语言I博客作业06
    linux下递归删除目录下所有exe文件
    CSS高级
    CSS样式
    CSS框模型
    Oracle的用户、角色和权限
  • 原文地址:https://www.cnblogs.com/utank/p/13262162.html
Copyright © 2011-2022 走看看