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;
}

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2020-02-18
猜你喜欢
  • 2022-03-01
  • 2021-05-21
  • 2021-09-10
  • 2021-09-24
  • 2021-08-20
  • 2021-12-05
相关资源
相似解决方案