zoukankan      html  css  js  c++  java
  • Swap Nodes in Pairs

    题目:Given a linked list, swap every two adjacent nodes and return its head.

    Given 1->2->3->4

    you should return the list as 2->1->4->3.

    思路:设立tail作为下一个list前一个结点,所以每次判断当前和之后是否为空

        看了一下思路,立即ACCEPTED。

    本题思路很多,但是方法的不同,会导致解决的难易程度。我在一开怎么都不会accepted,原因就是个别情况不能考虑。

    设立tail作为下一个list前一个结点,所以每次判断当前和之后是否为空。这是一大技巧,还有就是每次都是判断

    “head!=NULL&&head->next!=NULL”,并且设立一个暂时的tmp,迭代来讲,head指向head->next->next。技巧性还是有的。


    代码:

    /**
     * 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 *dummy=new ListNode(-1);
            ListNode *tail=dummy;
            
            while(head!=NULL&&head->next!=NULL){
                ListNode *tmp=head->next;
                head->next=tmp->next;
                tail->next=tmp;
                tmp->next=head;
                
                tail=head;head=head->next;
                
            }
            head=dummy->next;
            delete dummy;
            
            return head;
        }
    };



  • 相关阅读:
    Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (二) —— SQLite
    理解 Continuation
    99种用Racket说I love you的方式
    Racket Cheat Sheet
    scheme 教程 #lang racket
    开始学习Scheme
    MIT Scheme 的基本使用
    CPS变换
    SECD machine
    scheme 之门
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519918.html
Copyright © 2011-2022 走看看