• #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) {
            ListNode*  current = head;
            ListNode* pnext = NULL;
            ListNode* pre = NULL;
            ListNode* prePre = NULL;
            while(current != NULL && current->next  != NULL) {
                pre = current;
                current = current->next;
                pnext = current->next;
                if(pre == head) head = current;    //这是首次进行循环头指针的改变
                if(prePre) prePre->next = current;  //这步是关键步骤,一开始没想到过
                
                current->next = pre;
                pre->next = pnext;
     
                prePre = pre;   //保存前指针
                current = pnext;
            }
            return head; 
        }
    };
  • 相关阅读:
    网络基础
    Linux安装Redis
    mongodb——文档操作
    mangodb——集合的操作
    Linux安装MongoDB
    2021-10-14软件设计师
    2021-10-13
    How do you use System.Drawing in .NET Core?
    C# 9.0 新特性
    Mysql存储引擎
  • 原文地址:https://www.cnblogs.com/xiaohaigege/p/5482054.html
Copyright © 2020-2023  润新知