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

    Question

    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.

    解题思路

    这道题比较简单,但是要注意指针的应用,无非就是每次两两节点交换位置。然后还有就是要注意为空和为奇数个节点的情况。

    实现代码

    #include <iostream>
    
    using namespace std;
    
    //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 == NULL)
                return head;
            if (head->next == NULL)
                return head;
    
            if (head->next != NULL) {
                ListNode* p = head;
                ListNode* q = head->next;
                head = head->next;
                ListNode* r = NULL;
                while(1) {
                    p->next = q->next;
                    q->next = p;
                    if (r != NULL)
                        r->next = q;
    
                    if (p != NULL && p->next != NULL && p->next->next != NULL) {
                        r = p;
                        p = r->next;
                        q = p->next;
                    } else {
                        break;
                    }
                }
            }
            return head;
        }
    };
    
    int main() {
        ListNode* node1 = new ListNode(1);
        ListNode* node2 = new ListNode(2);
        ListNode* node3 = new ListNode(3);
        ListNode* node4 = new ListNode(4);
        ListNode* node5 = new ListNode(5);
        ListNode* node6 = new ListNode(6);
        node1->next = node2;
        node2->next = node3;
        node3->next = node4;
        node4->next = node5;
        node5->next = node6;
        Solution* solution = new Solution();
        ListNode* head = solution->swapPairs(node1);
        while(head != NULL) {
            cout << head->val << " ";
            head = head->next;
        }
    
        return 0;
    }
    
  • 相关阅读:
    运动习惯
    无伤跑法
    libopencv_videoio.so, need by /lib/libopencv_highgui.so, not found (try using -rpath or -rpath-link)
    HI3536安装交叉编译工具链
    ubuntu源码安装cmake
    error: ‘CV_BGR2GRAY’ was not declared in this scope
    U8 EAI实现XML的生成
    一个关于车牌识别的文章,感谢作者的分享
    常用的PHP框架
    10款免费而优秀的图表JS插件
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/6445147.html
Copyright © 2011-2022 走看看