• 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;
        }
    };
  • 相关阅读:
    Eclipse Mac OS 安装 Subversion插件subclipse 缺失JavaHL解决方案
    Eclipse Mac OS 安装 最新版 Subversion插件subclipse
    mac OS 安装 Homebrew软件包管理器
    Ribbon 框架简介及搭建
    Ribbon 框架简介及搭建
    TinyMCE下载及使用
    努力啊。
    逃离
    怎么学习
    烂代码
  • 原文地址:https://www.cnblogs.com/csudanli/p/5882123.html
Copyright © 2020-2023  润新知