Given a linked list, swap every two adjacent nodes and return its head.

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.

给一个链表,交换每两个相邻的结点,返回新链表。


二、解题报告

解法一:操作值域

直接交换结点的val是最简单的:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == NULL)
            return NULL;
        ListNode* first = head;
        ListNode* second = head->next;
        while(first!=NULL && second!=NULL) {
            int temp = first->val;      // 交换val
            first->val = second->val;
            second->val = temp;
            if(first->next!=NULL)
                first = first->next->next;
            if(second->next!=NULL)
                second = second->next->next;
        }
        return head;
    }
};


解法二:操作结点

题目要求:You may not modify the values in the list, only nodes itself can be changed. 好吧,那就来操作结点吧。

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == NULL)
            return NULL;
        ListNode* first = head;
        ListNode* second = head->next;
        ListNode* p = new ListNode(0);
        head = p;
        while(first!=NULL && second!=NULL) {
            ListNode* temp1 = first;
            ListNode* temp2 = second;
            if(second->next!=NULL)
                second = second->next->next;
            if(first->next!=NULL)
                first = first->next->next;
            p->next = temp2;
            p->next->next = temp1;
            p = p->next->next;
            p->next = NULL;
        }
        if(first!=NULL) {
            p->next = first;
        }
        return head->next;
    }
};

空间复杂度为





LeetCode答案源代码:https://github.com/SongLee24/LeetCode


相关文章:

  • 2021-12-07
  • 2021-05-31
  • 2022-03-10
  • 2021-09-04
  • 2021-12-28
  • 2022-02-16
猜你喜欢
  • 2021-06-02
  • 2021-09-24
  • 2021-10-31
  • 2022-01-26
  • 2021-07-05
  • 2021-06-27
  • 2021-07-12
相关资源
相似解决方案