博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode题目:Swap Nodes in Pairs
阅读量:6907 次
发布时间:2019-06-27

本文共 914 字,大约阅读时间需要 3 分钟。

题目: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.

题目解答:成对的调转链表中的节点。使用指针p和q表示当前待交换的两个节点。o代表了前一个节点。r表示后一个节点。

代码:

/**

 * 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 *Head = new ListNode(-1);
        Head -> next = head;
        ListNode *o = Head;
        ListNode *p = Head -> next;
        while(p != NULL)
        {
            ListNode *q = p -> next;
            if(q != NULL)
            {
                ListNode *r = q -> next;
                o -> next = q;
                q -> next = p;
                p -> next = r;
                o = o -> next -> next;
            }
            p = p -> next;
        }
        p = Head -> next;
        delete Head;
        return p;
    }
};

转载于:https://www.cnblogs.com/CodingGirl121/p/5425505.html

你可能感兴趣的文章
kafka - advertised.listeners and listeners
查看>>
Hadoop YARN学习监控JVM和实时监控Ganglia、Ambari(5)
查看>>
ECharts:免费,开源,超炫的可视化作品
查看>>
跨界 +赋能——互联网的下一个关键词
查看>>
argz_create函数
查看>>
vmware HA与vmware FT功能对比
查看>>
分区表添加分区的问题
查看>>
从数据库生成和控制treeview
查看>>
linux基础:vbox+ubuntu环境,常见命令+基本脚本编写与执行
查看>>
面向物联网的几大开源操作系统
查看>>
百度分享按钮代码
查看>>
openCV vs2013配置
查看>>
Resin优化方案
查看>>
GC参数整理
查看>>
前后端常见的几种鉴权方式
查看>>
Oracle11g DMP 文件导入到 10g
查看>>
双网卡同时使用配置
查看>>
恢复密码
查看>>
20180504早课记录03-Linux
查看>>
11.交换路由远程管理
查看>>