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.

     本文只需要两个指针依次交换相互位置。但是需要注意单数链表的情况。时间:4ms

    代码如下:

    /**
     * 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, *q, *phead, *pnext=new ListNode(0);
            p = head;
            q = head->next;
            phead = pnext;
            do{
                q = p->next;
                p->next = q->next;
                q->next = p;
                pnext->next = q;
                pnext = p;
                if (p != NULL)
                    p = p->next;
            } while (p != NULL&&p->next != NULL);
            return phead->next;
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    mysql创建表
    MySql数据类型(转)
    mysql命令总结
    php文件遍历类:FileBianli.class.php
    php文件删除
    php文件复制
    php文件遍历
    php下载c
    智能眼镜的行业应用
    《代谢增长论》读书笔记
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4547807.html
Copyright © 2011-2022 走看看