zoukankan      html  css  js  c++  java
  • LeetCode(24) 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.

    分析

    如示例所示,给定一个链表,要求交换链表中相邻两个节点。
    对于此题的程序实现,必须注意的是指针的判空,否则,一不注意就会出现空指针异常。

    AC代码

    /**
     * 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 || head->next == NULL)
                return head;
    
            ListNode   *p = head , *q = p->next;
            //首先交换头两个结点,同时保存q后结点
            ListNode *r = q->next;
    
            head = q;
            p->next = r;
            q->next = p;
            if (r && r->next)
            {
                ListNode *pre = p;
                p = p->next;
                q = p->next;
    
                while (q)
                {
                    //保存q结点后结点
                    ListNode *r = q->next;
    
                    pre->next = q;
                    p->next = r;
                    q->next = p;
                    if (r && r->next)
                    {
                        pre = p;
                        p = r;
                        q = p->next;
                    }
                    else{
                        break;
                    }
                }
            }
            return head;
        }
    };

    GitHub测试程序源码

  • 相关阅读:
    List集合
    ArrayList_toArray
    Collection集合基础知识
    Array类的使用
    16.10
    16.9
    16.8
    16.7
    16.6
    16.5
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214919.html
Copyright © 2011-2022 走看看