zoukankan      html  css  js  c++  java
  • LeetCode 24. Swap Nodes in Pairs

    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) {
            if (!head || !head->next)return head;
            ListNode* pre = head, *current = head->next,*next;
            pre->next = current->next;
            current->next = pre;
            head = current;
            if (!pre->next)return head;
            current = pre->next;
            next = current->next;
            while (current&&next)
            {
                current->next = next->next;
                next->next = current;
                pre->next = next;
                pre = current;
                if (!pre->next)return head;
                current = current->next;
                next = current->next;
            }
            return head;
        }
    };
  • 相关阅读:
    Oracle(二)常用操作语句
    Oracle(一)概念理解
    Spring MVC实现文件上传和下载
    Spring MVC 的执行流程
    Spring MVC原理及配置详解
    idea创建maven web项目
    Spring Bean的生命周期
    integer和int的区别
    web项目搜索框智能提示
    html-tab page
  • 原文地址:https://www.cnblogs.com/csudanli/p/5882123.html
Copyright © 2011-2022 走看看