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;
        }
    };
  • 相关阅读:
    C#
    C#
    C#
    python——socket网络编程
    Python——面向对象
    Python——函数
    Python——列表深浅拷贝
    Python——文件操作
    多级菜单(增强版)
    Python 编码机制
  • 原文地址:https://www.cnblogs.com/renrenbinbin/p/4341004.html
Copyright © 2011-2022 走看看