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.”
  • 相关阅读:
    母版
    扣点计算
    付费推广的投入产出比达到多少才合理?
    关于京东POP和采销双平台选择合作
    学习Swift--枚举的初步认识 --个人备忘 大神勿喷
    前台操作及技巧的一些文档
    ABAP 四舍五入函数
    设置ALV 行颜色
    初学笔记
    模块 BAPI
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4547807.html
Copyright © 2011-2022 走看看