zoukankan      html  css  js  c++  java
  • Leetcode: 24. Swap Nodes in Pairs

    Description

    Given a linked list, swap every two adjacent nodes and return its head.

    Example

    For example,
    Given 1->2->3->4, you should return the list as 2->1->4->3.
    
    Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
    

    思路

    • 首先使用两个指针指向要交换的节点,并且使用另外一个指针用来连接两对交换节点,也就是代码中的pre
    • 考虑好边界情况吧。算是个细心活

    代码

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            ListNode *res = NULL, *ptr = NULL, *cur = NULL, *pre = NULL;
            if(!head || !head->next) return head;
            
            ptr = head;
            cur = head->next;
            while(ptr && cur){
                //剩下链表的头结点
                head = cur->next;
                
                //交换
                cur->next = ptr;
                ptr->next = head;
                
                //头结点
                if(!res)
                    res = cur;
                
                //前面交换的后一个接上后面交换的前一个
                if(!pre)
                    pre = ptr;
                else{
                    pre->next = cur;
                    pre = ptr;
                }
                    
        
                ptr = head;
                if(head)
                    cur = head->next;
            }
            
            return res;
        }
    };
    
  • 相关阅读:
    leetcode 77 组合
    leetcode 40组合总和 II
    leetcode 216 组合总和III
    弹性伸缩 AS(Auto Scaling)
    弹性计算服务(Elastic Compute Service) / 云服务器 ECS
    云计算概述
    Zabbix Proxy 分布式监控
    Zabbix 自动发现 & 自动注册
    LVS-DR 模式
    GoAccess 监控工具
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6822730.html
Copyright © 2011-2022 走看看