• 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;
    }
    
  • 相关阅读:
    推荐2个Mac OS X上的JSON工具
    20个ios登陆界面
    IOS 真机调试和发布相关证书
    IOS学习路径
    Shell 语法和tips -- 持续更新
    Shell if 参数含义列表
    SimpleCursorAdapter 原理和实例
    Android Service VS AsyncTask VS Thread
    转:Intent 操作常用URI代码示例
    转:Android preference首选项框架
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/6445147.html
Copyright © 2020-2023  润新知