leetcode 题解 || Swap Nodes in Pairs 问题[通俗易懂]

leetcode 题解 || Swap Nodes in Pairs 问题

大家好,又见面了,我是全栈君。

problem:

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.

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

在单链表中。每两个结点交换一下位置。单个的不交换

thinking:

leetcode 题解 || Swap Nodes in Pairs 问题[通俗易懂]

(1)这道题在不新建结点的情况下。指向关系复杂。慢慢分析

(2)head是头指针,指向第一个有效结点!

code:

/**
 * 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 *index = head;
        ListNode *pre = NULL;
        ListNode *tmp = NULL;
        ListNode *modify = head;;
        int i=0;
        if(head==NULL||head->next==NULL)
            return head;
        while((index!=NULL)&&(index->next!=NULL))
        {
            i++;
            pre=index;
            if(i==1)
            {
                head=pre->next; 
                index = index->next;
                tmp = index->next;
                pre->next = tmp;
                index->next = pre;
                index=tmp;
                modify=pre;
            }
            else
            {
                index = index->next;
                tmp = index->next;
                modify->next=pre->next;
                pre->next = tmp;
                index->next = pre;
                index=tmp;
                modify=pre;
            
            }
           
                
        }
        return head;
    }
};

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/115548.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • python pip升级命令

    python pip升级命令因为pip升级不常用到,所以经常不记得,趁现在记录一下pipinstall–upgradepip

    2022年6月9日
    41
  • 卸载oracle数据库

    卸载oracle数据库

    2021年11月14日
    45
  • 微商分销功能不能用了

    微商分销功能不能用了“三级以上分销将会被停止支付功能和封停账号”,日前一则“不利”消息彻底引爆微商的主要阵地——微信朋友圈。一时间关于分销三级变二级、微商寒冬将至的说法再次疯传。自央视曝光部分微商涉嫌传销之后,微信今年接连对微商们“动刀”,强化管理意在行业正规化发展,失去多级分销之后,依靠内容深度揽客的方式成为微商转型的方向。微商连遭重创刚刚过去的一周,微商们再次体验到了人生的跌宕起伏。认证为腾讯微信

    2022年5月13日
    45
  • jenkins allure_allure测试报告

    jenkins allure_allure测试报告前言jenkins集成了allure插件,安装插件后运行pytest+allure的脚本即可在jenkins上查看allure报告了。allure安装在运行代码的服务器本机,我这里是用的dock

    2022年7月29日
    23
  • 移植 libuv 至 Visual C++ 6.0 并支持 Windows XP 编译系统

    移植 libuv 至 Visual C++ 6.0 并支持 Windows XP 编译系统

    2022年1月16日
    86
  • fstream与sstream

    fstream与sstream#include是C++的预编译语句,作用是包含对应的文件,在这里是包含C++的STL头文件fstream。在包含了这个文件后,就可以使用fstream中定义的类及各种成员函数了。fstream是C++STL中对文件操作的合集,包含了常用的所有文件操作。在C++中,所有的文件操作,都是以流(stream)的方式进行的,fstream也就是文件流filestream。最常用的两种操作…

    2022年6月3日
    43

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号