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;
    }
    
  • 相关阅读:
    程序员第一定律:关于技能与收入
    JS注册/移除事件处理程序
    关于程序猿,你不知道的15件事
    .NET后台输出js脚本的方法
    新项目经理必读:分析什么是项目经理
    项目如何开始:怎样和客户一起搞定需求
    【转】为什么程序员讨厌修改静态检查问题
    js的with语句使用方法
    软件版本号 详解
    PHP记忆碎片2投票汇总
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/6445147.html
Copyright © 2011-2022 走看看