zoukankan      html  css  js  c++  java
  • Leetcode swap-nodes-in-pairs(链表 交换相邻节点)

    题目描述

    将给定的链表中每两个相邻的节点交换一次,返回链表的头指针
    例如,
    给出1->2->3->4,你应该返回链表2->1->4->3。
    你给出的算法只能使用常量级的空间。你不能修改列表中的值,只能修改节点本身。
     
     

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

    For example,
    Given1->2->3->4, you should return the list as2->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 *res = new ListNode(0);
            ListNode *p=res;
            if(head==NULL||head->next==NULL)
                return head;
            ListNode *l=head;
            ListNode *r=l->next;
            while(l!=NULL&&r!=NULL)
            {
                p->next=r;
                l->next=r->next;
                r->next=l;
                p=l;
                l=p->next;
                r=l->next;
            }
            return res->next;
        }
    };
  • 相关阅读:
    JSP 学习笔记1
    XML scriptlet 连接数据库
    JSP 定义行列数表单创建表格
    JSP_01
    JS创建表格完整
    04-基本的mysql语句
    03-MySql安装和基本管理
    02-数据库概述
    01-MySql的前戏
    爬虫系列
  • 原文地址:https://www.cnblogs.com/zl1991/p/12799219.html
Copyright © 2011-2022 走看看