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.”
  • 相关阅读:
    找到搜索的北了
    zoj2741Offside
    hdu: 1426 ( Sudoku Killer )
    悲剧的矩阵乘法
    UVa729 The Hamming Distance Problem
    hdu 1584 蜘蛛牌
    zoj2972Hurdles of 110m
    hdu 1372 ( Knight Moves ) BFS
    UVa193Graph Coloring
    zjut1624序列问题
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4547807.html
Copyright © 2011-2022 走看看