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;
        }
    };
  • 相关阅读:
    大道至简观后感
    冲刺第二天
    梦断代码阅读笔记 02
    冲刺第一天
    第十周学习进度
    个人冲刺第一阶段个人任务--界面
    软工第二周个人作业
    软件工程开课博客(自我介绍)
    梦断代码阅读笔记01
    第二周学习进度报告
  • 原文地址:https://www.cnblogs.com/zl1991/p/12799219.html
Copyright © 2011-2022 走看看