zoukankan      html  css  js  c++  java
  • LeetCode 24

    一、问题描述

    Description:

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

    For example:

    Given 1->2->3->4, you should return the list as 2->1->4->3.

    Note:

    Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

    给一个链表,交换每两个相邻的结点,返回新链表。


    二、解题报告

    解法一:操作值域

    直接交换结点的val是最简单的:

    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            if(head == NULL)
                return NULL;
            ListNode* first = head;
            ListNode* second = head->next;
            while(first!=NULL && second!=NULL) {
                int temp = first->val;      // 交换val
                first->val = second->val;
                second->val = temp;
                if(first->next!=NULL)
                    first = first->next->next;
                if(second->next!=NULL)
                    second = second->next->next;
            }
            return head;
        }
    };


    解法二:操作结点

    题目要求:You may not modify the values in the list, only nodes itself can be changed. 好吧,那就来操作结点吧。

    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            if(head == NULL)
                return NULL;
            ListNode* first = head;
            ListNode* second = head->next;
            ListNode* p = new ListNode(0);
            head = p;
            while(first!=NULL && second!=NULL) {
                ListNode* temp1 = first;
                ListNode* temp2 = second;
                if(second->next!=NULL)
                    second = second->next->next;
                if(first->next!=NULL)
                    first = first->next->next;
                p->next = temp2;
                p->next->next = temp1;
                p = p->next->next;
                p->next = NULL;
            }
            if(first!=NULL) {
                p->next = first;
            }
            return head->next;
        }
    };

    空间复杂度为O(1)





    LeetCode答案源代码:https://github.com/SongLee24/LeetCode


  • 相关阅读:
    UITableView多选全选
    iOS16进制设置颜色
    svg矢量图
    canvas 时钟案例
    canvas 方块旋转案例
    canvas万花筒案例
    swiper(轮播)组件
    canvas介绍(画布)
    scroll-view组件
    view组件
  • 原文地址:https://www.cnblogs.com/songlee/p/5738042.html
Copyright © 2011-2022 走看看