美文网首页
Swap Nodes in Pairs

Swap Nodes in Pairs

作者: CarlBlack | 来源:发表于2016-01-04 21:33 被阅读0次

    标签: C++ 算法 LeetCode 链表

    每日算法——leetcode系列


    问题 Swap Nodes in Pairs

    Difficulty: Medium

    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.

    /**
     * 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) {
            
        }
    };
    

    翻译

    一对一对的交换节点

    难度系数:中等
    给定一个链表,交换相邻的两个节点并返回。
    例如:
    给定1->2->3->4, 你返回的链表应该是 2->1->4->3
    算法的空间复杂度应该为常数级, 不能修改链表中的节点的值,只有节点的可以换。

    思路

    链表的题画图比较清晰,本题就是找当前节点的下一个节点和前一个节点。
    假设: cur代表当前节点,pre代表前一个节点,next代表下一个节点
    两两交换就是:
    cur->next = next->next;
    next->next = cur;
    pre->next = next;

    代码

    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            ListNode* pre = new ListNode(-1);
            ListNode* cur = head;
            for ( ; cur != nullptr && cur->next != nullptr; cur = cur->next){
                ListNode* next = cur->next;
                cur->next = next->next;
                next->next = cur;
                pre->next = next;
                pre = cur;
                if (cur == head){
                    head = next;
                }
            }
            return head;
        }
    };
    

    注:上面的代码有new,但没释放,这个不好,可以在指向其他节点的时候先存一份,完了再删。也可以直接用nullptr初始化, 由于nullptr无next节点用的时候注意nullptr的情况

    相关文章

      网友评论

          本文标题:Swap Nodes in Pairs

          本文链接:https://www.haomeiwen.com/subject/ntjahttx.html