zoukankan      html  css  js  c++  java
  • 24.两两交换链表中的结点

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

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

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

    递归

    这个问题存在子问题。去掉头两个结点之后仍然是相同的一类问题,因此可以交换头两个结点,剩余结点递归处理。

        ListNode* swapPairs(ListNode* head) {
            if(!head||!head->next) return head;
            ListNode*temp=head->next;
            head->next=swapPairs(head->next->next);
            temp->next=head;
            return temp;
        }
    

    迭代

    常规做法,遍历结点。链表中交换结点需要同时顾前和顾后,需要有一个pre指针指向两结点之前的一个结点

    模型:pre->l1->l2->rest (l1,l2为待交换的两个结点)

        ListNode* swapPairs(ListNode* head) {
            if(!head||!head->next) return head;
            ListNode*l1=head,*l2=head->next,*dummy=new ListNode(-1),*pre=dummy;
            while(l1&&l1->next){
                l2=l1->next;
                //交换结点
                l1->next=l2->next;
                l2->next=l1;
                pre->next=l2;
                //更新结点
                pre=l1;
                l1=l1->next;
            }
            return dummy->next;
        }
    

    leetcode链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs

  • 相关阅读:
    Storm 第一章 核心组件及编程模型
    四 Hive整合HBase
    Hbase第五章 MapReduce操作HBase
    swift 附属脚本
    swift 方法
    swift 属性
    swift 类和结构体
    swift 枚举类型
    swift 闭包
    Swift 函数
  • 原文地址:https://www.cnblogs.com/Frank-Hong/p/13475237.html
Copyright © 2011-2022 走看看