LeetCode 24 Swap Nodes in Pairs

2019-07-08 17:39:19 浏览数 (1)

题目

代码语言:javascript复制
/**
 * 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* res = head;
        ListNode* term = res;
        while(head!=NULL)
        {
            if(head->next!=NULL)
            {
                ListNode* temp = head->next;
                
                head->next = temp->next;
                temp->next = head;
                term->next = temp;
                
                 term=head;
                head=head->next;
              
            }
            else
                break;
        }
        return res;
    }
};

0 人点赞