• 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.

    Subscribe to see which companies asked this question

    /**
     * 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 (NULL == head || NULL == head->next) {
                return head;
            }
            //模拟头结点,方便计算
            ListNode fake(0);
            ListNode* node = &fake;
            node->next = head;
            //从头结点开始进行翻转
            while (node && node->next) {
                node->next =  swap(node->next);
                node = node->next->next;
            }
            return fake.next;
        }
        //返回翻转之后的头结点
        ListNode* swap(ListNode* p) {
            ListNode* q = p->next;
            if (NULL == q) {
                return p;
            }
            ListNode* tmp = q->next;
            q->next = p;
            p->next = tmp;
            return q;
        }
    
    };
  • 相关阅读:
    antd的form表单4.0
    antd的select搜索展现错误
    ts的枚举类型简化if else if判断
    深入解读webpack
    常用es6语法总结
    手动配置webpack
    apply,all,bind的区别
    面试题小结
    react中根据后台值动态配置
    react动态路由以及获取动态路由
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5119747.html
Copyright © 2020-2023  润新知