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

    https://oj.leetcode.com/problems/swap-nodes-in-pairs/

    链表的处理

    /**
     * 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 *dummy = new ListNode(-1);
            if(head == NULL)
                return dummy->next;
            
            dummy->next = head;
            
            ListNode *tail = dummy;
            
            ListNode *current = head;
            ListNode *second = head->next;
            while(current && second)
            {
                tail->next = second;
                current->next = second->next;
                second->next = current;
                
                current = current->next;
                if(current == NULL)
                    break;
                second = current->next;
                tail = tail->next;
                tail = tail->next;
                
            }
            return dummy->next;
        }
    };
  • 相关阅读:
    11.29
    11.28
    11.24
    11.21
    11.17
    11.15
    11.14
    11.9
    11.5
    11.3
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3916903.html
Copyright © 2011-2022 走看看