zoukankan      html  css  js  c++  java
  • #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; 
        }
    };
  • 相关阅读:
    Sumdiv POJ
    Tallest Cow POJ
    P2280 [HNOI2003]激光炸弹(二维前缀和)
    Strange Towers of Hanoi POJ
    Manjaro (KDE)安装踩坑记录
    Petya and Array CodeForces
    CodeForces
    Philosopher’s Walk(递归)
    2018 icpc 青岛网络赛 J.Press the Button
    POJ 1003: Hangover
  • 原文地址:https://www.cnblogs.com/xiaohaigege/p/5482054.html
Copyright © 2011-2022 走看看