zoukankan      html  css  js  c++  java
  • Swap Nodes in Pairs 分类: Leetcode 2014-12-06 19:58 80人阅读 评论(0) 收藏

    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.

    一次就过了,简直就不敢相信,其实就是简单的两值互换。

    /**
     * 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 *p;
            p=head;
            int temp;
            if(!p) return p;
            if(!p->next) return p;
            while(p && p->next)
            {
                temp=p->val;
                p->val=p->next->val;
                p->next->val=temp;
                p=p->next->next;
            }
            return head;
            
        }
    };


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    oracle 存储过程
    IBM Http Server 7 下载安装
    设置linux静态IP地址
    was7补丁下载安装
    JDBC提供程序和数据源配置
    db2替换激活永久lic
    db2基本命令
    db2创建数据库
    linux解压命令
    linux下安装db2_v9.7
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656984.html
Copyright © 2011-2022 走看看