zoukankan      html  css  js  c++  java
  • 24. Swap Nodes in Pairs

    description:

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

    You may not modify the values in the list's nodes, only nodes itself may be changed.
    Note:

    Example:

    Given 1->2->3->4, you should return the list as 2->1->4->3.
    

    my answer:

    感恩

    画图,没有难点,就是两个两个来回挪,要设置pre指向要挪的两个节点的前面那个节点, t指向要挪的两个节点的后面那个节点。

    
    

    大佬的answer:

    /**
     * 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), *pre = dummy;
            dummy->next = head;
            while(pre->next && pre->next->next){
                ListNode* t = pre->next->next;
                pre->next->next = t->next;
                t->next = pre->next;
                pre->next = t;
                pre = t->next;
            }return dummy->next;
        }
    };
    

    relative point get√:

    hint :

  • 相关阅读:
    ES5数组扩展
    ES5给object扩展的一些静态方法
    poj2531-dfs
    快排
    阶段性总结-贪心算法
    日常算法题
    poj1979 解题报告
    poj 2586
    poj3069
    poj2709 解题报告
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/10888371.html
Copyright © 2011-2022 走看看