LeetCode-206-单链表逆序

问题描述

LeetCode - Reverse Linked List

将单链表逆序

算法1 插入法

性能:
Runtime: 4 ms, faster than 89.98% of C online submissions for Reverse Linked List.

算法思路:
类比于插入排序,两个指针 first 和 last 分别指向已经逆序好的开头和结尾,即 first->x->x->last->NULL

  1. 开始时,first和last都指向head。
  2. 然后从 head->next 开始,遍历链表,将每个节点 p 插入到(first,last)的开头,即p->fist->x->x->NULL

代码如下

struct ListNode* reverseList(struct ListNode* head){
    if (head->next == NULL) return head;

    struct ListNode* first = head; // (first, last) 是已经逆序的部分,first->xx->last
    struct ListNode* last = head;

    // 遍历链表,往前插入
    struct ListNode* p = head->next;
    last->next = NULL;

    while(p != NULL) {
        // first->xxx->head, 插入p,变为 p->first->xx->head

        struct ListNode* pNext = p->next; // 先记录p->next
        p->next = first;
        first = p;

        p = pNext;
    }

    return first;
}

C solution fast than 89.98%, Similar to Insert Sort algorithm

算法2 新增一个头节点pre,不断将数据插入pre后面

C++ Iterative and Recursive
这是discuss区一个vote较高的答案,思路和我的算法很像,都是插入。
不过,它是新增了一个头结点pre,然后遍历链表,不断的把节点,插入到pre后面

(1) 新增节点pre, pre->next 指向 head, 即 (pre->head)
(2) cur 指向 head,不断的把 cur->next 插入到 pre 和 head 之间. ( cur 位置不变,始终是指向head的。但是随着插入的进行,cur->next 不断往后了)

比如原List是 1->2->3->4->NULL,那么新增一个pre,变成pre->1->2->3->4->NULL,cur始终指向head,即 1,但是随着插入的进行,cur->next 依次变成了2,3,4

struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode *pre = malloc(sizeof(struct ListNode));
    struct ListNode *cur = head;
    pre -> next = head;
    while (cur && cur -> next) {
        struct ListNode* temp = pre -> next;
        pre -> next = cur -> next;
        cur -> next = cur -> next -> next;
        pre -> next -> next = temp;
    }
    return pre -> next;
}

算法4 插入法更精简写法

从所有递交结果中捞出的速度最快的算法

点击0位置的阴影块即可看到算法

思路和算法1一样,相当于 prev 就是first,head就是last。只是更精简而已。
(prev, head) 是已经逆序的,然后不断head往后走,然后把head->next插入到开头。

struct ListNode* reverseList(struct ListNode* head) {
    if (head == NULL || head->next == NULL) return head;

    struct ListNode* prev = NULL;
    while (head != NULL) {
        struct ListNode* temp = head;
        head = head->next;
        temp->next = prev;
        prev = temp;
    }
    return prev;
}

算法5 递归

struct ListNode* reverseList(struct ListNode* head) {
    if (head == NULL || head->next == NULL) return head;
    struct ListNode* node = reverseList(head->next);
    if (head->next->next == NULL) printf("NULL\n");
    head->next->next = head; // head->next 就是 node所逆序链表的最后一个元素
    head->next = NULL;
    return node;
}

Related: rotterdam zoo animal list, strip light mounting brackets, la femme prom dresses near me, used ringmaster lathe for sale, apartments in alexandria, va under $1,300, le ciel de paris eiffel tower restaurant, earth rod installation cost, science diet large breed 6, mobile homes for sale in shelley, idaho, christina cosmetics official website, mens chelsea boots clearance sale, exotic fruit trees for sale near me, small aloe plant care, how to apply for housemaid visa in bahrain, radiology research opportunities for medical students,Related: dryer knob shaft broken, what does itira korgath metin mean, robert taylor obituary, estate agents jedburgh scottish borders, what values encourage misconduct, grainger county tomatoes shipped, buena vista correctional complex inmate mail, what is prestonplayz real phone number 2021, comcast cable box secret menu, hunt county property tax search, jani lane daughter died, douglas eugene franco cause of death, old testament disobedience and retribution examples, feels like i'm peeing my pants but i'm not, an ancient was spotted on the triple peninsula,Related: mebeverine and omeprazole together furosemide, beaver county accident yesterday, kathy keller obituary, pip enhanced mobility mental health 2021, signs a female doctor is attracted to you, discovery plus not working on sky q, how to stop my wandering eyes, will a 4x8 sheet of plywood fit in a tahoe, aldi pro heavy duty grout cleaner, accidentally sanded lead paint, robin trower wife, danielle bower abc, huski chocolate stockists uk, sa isang noontime show o pantanghalan variety show, tongue thrust exercises for adults,Related: robinson family boerboel, everyday will be sunday sabbath will have no end, 1615 northern blvd, manhasset, ny 11030, 5 letter words with button, fred lauper wrestler, stevens 555 choke tubes for sale, life at fmc devens, ryan and nolan wheaton, monique watson found alive, titanium network proxy site, 2 way zipper pajamas 12 18 months, how long do i need to wait before using afrin again minocycline, alaska airlines flight 1866, does a tow dolly need a license plate in texas, founders company louisville ky vodka,Related: serenity funeral home obituaries roanoke, va, johnston county virtual academy 2021 2022, new home construction timeline after drywall, kaii mccargo uniontown ,pa obituary, 1 bed flat to rent medway dss, persepolis panel analysis, roman atwood new house zillow, upper circle theatre, are recitals in a court order enforceable, shooting in martinsburg, wv yesterday, obfz prievidza futbalnet, is david mulroney related to brian mulroney, list of governors of ilocos norte, who is kaavia james biological father, new york city catholic orphanage records,Related: is tints of nature henna cream safe, reggie ballard the wire, rv lots for sale in destin florida by owner, punta cana homes for sale zillow, bhasvic notable alumni, hobby lobby cardboard letters, legal newsletter names, gamble funeral home fire, was there a real john stroud at the alamo, my toddler inhaled my vape what to do, phil and the blanks band new richmond wi, simon sadler wealth, marquette park crime, average shot put throw for college, sturgis biker women campground pictures,Related: who is china allies with 2022, department of community affairs nj inspection, lewis dot structure for rubidium phosphide, do all the eggheads get on, countess estelle marie carandini di sarzano, 7 on your side los angeles contact, suramin spike protein, fire officer professional development plan, meredith stutz eye, what time does green dot post tax refunds, bausch and lomb horizon rewards visa card balance, icon golf cart charging issues, anthony richards catalog clearance, 1 pound of ground pork is how many cups, examples of ethos in i have a dream speech,Related: pioneer academics timed writing, mark mcgowan conference, morosil blood orange extract drug interactions, candide optimism theme, marseille airport covid test, john morgan winmark net worth, secrets akumal oceana menu, barred door picheringa ac valhalla, chances of bad news at 20 week scan mumsnet, nepean private hospital parking rates, rosie jones comedian net worth, st nicholas greek orthodox church festival, albuquerque fire department lateral hiring, apartments for rent in port st lucie under $1000, to the lake anya death,Related: can chickens eat kohlrabi greens, northern kentucky obituaries, deauville score 4 prognosis, somalia elephant silver coin mintage, greta scacchi and carlo mantegazza, me meti el dedo y siento algo raro, post university laptop program, burberry inbound logistics, swati kovind marriage, 3aw code word today, disadvantages of barzona cattle, cannonball architecture, is body autonomy a human right, gwen mctavish new zealand, shooting in new britain, ct today,Related: gammon steak recipes gordon ramsay, orari messe san lorenzo in banale, apartments kalispell, mt, troubadour golf club members, nebraska dhhs child protective services, did marlon jackson have a heart attack, solar system lesson plans 6th grade pdf, rainbow six extraction not showing on gamepass, car accident in virginia beach last night, manchester, nh arrests 2022, mecklenburg county mugshots, sf6 circuit breaker ratings, restaurants that accept ebt in victorville, ca, ponytail shag haircut, start up expenses examples,Related: is elizabeth perkins related to millie bobby brown, antioch district 34 superintendent, classic car shows 2021 essex, does motel 6 require a security deposit, unsolved murders in kingman az, winkler puppies for sale, reed funeral home kinder la obituaries, bank mobile vibe customer service, philtrum filler before and after, oregon obituaries today, sasha samsudean background, bronny james stats last night, timeless look magnolia paint, compustar remote start starts then shuts off, who makes this cigarettes,Related: what happened to leigh diffey, alexander serpico biography, sue barker wedding pictures, mobile homes for sale in ranburne, al, william harvey hospital consultants, iu basketball radio stream, how old was lynyrd skynyrd when he died, shooting in decatur, il today, where does karen mcdougal live now, florence and the machine running up that hill, disney princess creator, poundland reed diffuser, tour pros using edel putters, knitting brioche in the round, alexandra wallace ucla where is she now,Related: andrew castle daughter wedding, secondary movement of tadasana, hotels for rugby world cup 2023, rockwood geo pro accessories, 1 million de vue sur tiktok prix, tntp leadership coach salary, when does vanessa find out she's a van helsing, pros and cons of conservatism, behavioral hospital of bellaire ceo, spotify api without authentication, i hear the angels sing hallelujah, knuckles down in golf takeaway, ucsd public relations, is will demps married, portugal to madeira ferry,Related: pedersoli harpers ferry rifle, how to clear memory on walgreens blood pressure monitor, evening courses bournemouth, sims 4 video game override mod, how many points is a speeding ticket in nj, most dangerous neighborhoods in kansas city kansas, why did donkmaster go to jail for 6 months, can i get a tattoo before gallbladder surgery, 876957385c9d4e50873603 vizsla breeders north west uk, how long does cyproheptadine stay in your system, body found in middlesboro, ky, number of holocaust survivors 2021, still sad 10 years after divorce, food stamp eligibility calculator, shannon allman net worth,Related: baldwin county sheriff's office civil division, dave rozema kick, yale dnp executive leadership, fannie mae business mileage depreciation factor 2020, brink's bank mobile deposit limit, cyberpunk 2077 door code troublesome neighbors, xenia baseball tournament, tn state employee raises 2022, former weau news anchors, jackson mi bus schedule, zillow houses with mother in law suite, grady's pizza sauce recipe, carmarthenshire county council property to let, harry potter fanfiction petunia takes harry to gringotts, four more than twice a number,Related: vjersha per vitin e ri tekste shqip, david cook blockbuster founder net worth, korea quarantine facility food, aliso niguel high school graduation 2022, pentair communication to discovery service failed, janis putelis high school, markwayne mullin military service, how to clean electrolux oven racks, albert einstein college of medicine white coat ceremony 2022, starbucks vanderbilt medical center, did stevie ray vaughan have children, steve morris obituary, se7en how was sloth alive, how to get feathered theme in excel, shannon aikau net worth,Related: 2007 honda accord ac pressure switch location, reactants and products calculator, harmony 650 remote setup without computer, disposing of an activity to release suspended passive losses, mckesson connect api, mwo pilot tiers, gustavo rivera wife martha rivera, battletech alpha strike commander's edition pdf, shona baby names, hilton discount codes flyertalk, ark longneck rifle ammo gfi, did germany have nuclear weapons in ww2, aero linen fresh surface disinfectant msds, where to find motorcycles in gta 5 map, baby with big cheeks disease,Related: latin phrases about honor, red light therapy lamp, tony accardo testimony, how many refunds does xbox allow, bryan hoppy, how to print a schedule from dayforce, warren jeffs spouse naomi, titanic survivors interview, oakland county friend of the court, supporting documents for passport renewal, greenwich beach pass non resident, magnus ver magnusson heart attack, kimball furniture victorian reproductions, the parent trap symbolism, does minute maid fruit punch have caffeine,Related: puns for the name ari, kara leigh dimon, suing seller for non disclosure illinois, hagon motorcycle shocks usa, how to find an artesian well on your property, buckhead theater covid rules, nemesis ultimate behavior engine crash, alabama voter registration card replacement, al levantin birder, olivier desmarais wedding, lisa scottoline stand alone books, , marvel legends retro collection wave 2, justin spitzer hometown, big bend dam south dakota fishing report,Related: diana archer mills, mick martin and the blues rockers schedule, kamene okonjo biography, lost ark broken equipment powder, scpdca com community association, alexander jones five more minutes, arduino vs raspberry pi vs micro:bit, qut shuttle bus, santa rosa county jail mugshots, picrew character maker, normal thyroid size in cm, mercedes radar sensor dirty warning, can vaping cause esophagitis, was the smarter sentencing act 2021 passed, unable to locate a business with a matching asic key,Related: weatherford fire academy cost, bill bixby funeral, concerts in dubrovnik september 2022, ophthalmologist whanganui hospital, brian stewart obituary, ffxiv deep designs liver location, southwest boeing 737 max 8 seat map, shooting in jasper, florida, tcatt mike ferguson and mike gibson pictures, housing for parolees in michigan, pcso long service medal, polylogarithmic vs linear, mary tillman obituary, winecup gamble ranch lawsuit, avenue 5 residential lawsuit,Related: letter from william fitzhugh who is involved, trabajo de limpieza en escuelas, downtown memphis construction, ochr philadelphia operations center, wilkes county jail mugshots, why did michael easley leave fellowship bible church, bayview funeral home albert lea, mn, amy wilson married to bailey chase, , blonde hair blue eyes facts, where is mema from hollywood hillbillies, corn pop was a bad dude transcript, similes about climate change, who is the black girl in the nugenix commercial, john the baptist vs john the savage,Related: 1960 topps printable checklist, cooper test standards bench press, clearance mobile homes nc, smuckers coffee machine error codes, used wrecker trucks for sale in georgia, raffel systems touchscreen and controller, dfs lrc hm lcd, arrests and mugshots, fox 10 news anchors john hook, hf, rug tufting class near orlando, fl, barbara ruick cause of death, wayne newton daughter wedding, creature features kofy, inboxdollars daily activity, used traxxas trx4 for sale,Related: mobile homes for sale in strawberry, az, tooting stabbing 2021, parker az webcam, what happened to dan from the slow mo guys 2020, 2007 mercury mountaineer problems, td ameritrade invalid session, san marino high school principal, nahunta pork center weekly specials, funeral notices oamaru, timeshare resale companies under investigation, my five wives where are they now 2021, glover funeral home macon, ga, obituaries morris, il, alternative to boots curl creme, snowflake format timestamp,Related: marigold wilting after transplant, william hubbard south carolina, discovery magnet school lottery, is cleverbot safe, regional property manager bio, cleveland fire department archives, 10 yard rmr zero, what kind of gelatin is in great value yogurt, westview apartments mohegan lake, ny, how many rugby players have been paralyzed, mobile homes for rent in white bluff, tn, mark chenoweth theology, the difficult truth about dentures, bsa citizenship in society powerpoint, jane moore blue dress today,Related: nathan ellis director, how successful was the muslim league in 1937 elections, page 3 girl images, dynamic tattoo ink allergy, dermacolor camouflage cream boots, injecting mercury into boxing gloves, how to tell if your on a three way call, selenis leyva husband, brian jones cause of death, my girl thomas j death, what is the rarest item in prodigy 2021, american tomahawk company taiwan, joan f addis, how many countries use celsius, sunbrella sensibility spring,Related: pat narduzzi house, codice identificativo univoco farmacie elenco, spark read text file with delimiter, is massive action apparel legit, obituary joan murphy death heartland, how to use web shooters minecraft heroes expansion, douglas county recent arrests, can you eat lentil pods, frankfurt school 11 point plan, sun city, az obituaries 2022, who is the mother of anderson cooper's son wyatt, brown trout fingerlings for sale nsw, tim winton the turning small mercies summary, university of arizona dorms ranked, country bars with mechanical bull near frankfurt,Related: redneck island: where are they now, johnston county district attorneys office, paula sundsten merry prankster, citrix export list of published applications, mobile homes for sale hamilton, ohio, miniature schnauzer litters, a student strikes a block at the bottom of a ramp giving it an initial speed, grande prairie obituaries 2021, mario kart 8 loading screen characters, true courage is not the absence of fear, funeral homes monroe, nc, french beauty business names, umd bulldogs volleyball: roster, no two snowflakes are alike: translation as metaphor, year wise rainfall data gujarat,Related: , similarities between indigenous media and library, nordstrom chicken salad sandwich recipe, why does my avocado taste salty, 16634559fd7aacf465e91bd41 newsletter sign up phone number, ford super duty coil spring rates, george costigan obituary, connie foley obituary, merton council refuse collection complaints, balance of nature commercial actors, fear factor couples where are they now, saddleback high school edward bustamante, northern california rockhounding map, brooklyn center youth basketball, feeling nauseous when bending down,Related: can nurse practitioners prescribe adderall in florida, door to door barrel shipping to jamaica cost, rockingham nc events calendar, frances bavier obituary, future stars softball tournament ohio 2021, robert powell berkeley, leathered marble pool deck, puerto rico trench gravity anomaly, kaiju paradise golden pup chance, women's soccer strength training program, bat knees prosthetic legs ceo, lessons from antiquity something to fear, robert flynn obituary, huntington hospital internal medicine residency, king of world man,Related: what percentage does care credit charge providers, does glenn robbins have a glass eye, carnival cruise vifp lookup, jury duty questionnaire florida, ohio state wexner medical center apparel, who owns clearview cancer institute, names of guards killed at attica, microsoft c++ 2017 redistributable x64 windows 10, famous cryptorchid stallions, dr raine plastic surgeon deaths, , marshall high school basketball roster, duck dynasty cast member dies in accident, how much of the earth's land surface is desert, my girlfriend never says goodnight,Related: ian bleasdale isle of man, tying wrists with a necktie, bradford pa police reports, macedonian funeral food, why is shout stain remover hard to find, deepglow skate infect counters, graham crackers and milk before bed, barriers to community participation and social inclusion, when a door closes a window opens bible verse, imperial moth symbolism, paul o'neill son doctor, living in the woods homeless, how long does applicant insight background check take, what is graphic customization alibaba, sofia the first characters friends,Related: martin senour crossfire, how to connect a landline phone to a modem, alan badel obituary, mountain huckleberry plants for sale, michael helgoth handwriting, ecaytrade used appliances, ohio state psychiatric hospital, monthly numerology forecast, homes for sale in lexington, ky by owner 40509, autobus siena roma fiumicino, amsec esl20 factory reset combination, louis vuitton global ambassador list, map of gatlinburg strip, nh lottery second chance, oakridge mall map,

作者:JarvisChu
原文链接:LeetCode-206-单链表逆序
版权声明:自由转载-非商用-非衍生-保持署名 | Creative Commons BY-NC-ND 3.0

发表评论