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

    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.

    思路:就是遍历。

    注意:1.使用p->next时,一定要先检查p!!2.注意边界情况:空,1个,边界。

    还有其他思路::1.递归! 2.point** 更改指针的地址?????待会看

    /**
     * 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 *p1,*p2;
            p1=p2=head;
            if(p1 && p1->next) head=p1->next;
            while(p1 && p2 && p1->next){
                p2=p1->next->next;
                p1->next->next=p1;
                if(p2 && p2->next) p1->next=p2->next;
                else p1->next=p2;
                p1=p2;
            }
            if(p1 && p1->next) p1->next->next=p1;
            return head;
        }
    };
  • 相关阅读:
    winform 计算器
    ajax无刷新上传图片
    Dapper的基本使用
    补充1
    Ajax2
    Ajax1
    jQuery2
    Select查询语句2
    jQuery1
    分页与组合查询
  • 原文地址:https://www.cnblogs.com/renrenbinbin/p/4341004.html
Copyright © 2011-2022 走看看