摘要:新建兩個鏈表,分別存和的結(jié)點(diǎn)。令頭結(jié)點(diǎn)分別叫作和,對應(yīng)的指針分別叫作和。然后遍歷,當(dāng)小于的時候放入,否則放入。最后,讓較小值鏈表尾結(jié)點(diǎn)指向較大值鏈表頭結(jié)點(diǎn),再讓較大值鏈表尾結(jié)點(diǎn)指向。
Problem
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
ExampleGiven 1->4->3->2->5->2->null and x = 3,
return 1->2->2->4->3->5->null.
新建兩個鏈表,分別存
public class Solution { public ListNode partition(ListNode head, int x) { ListNode dummyleft = new ListNode(0); ListNode dummyright = new ListNode(0); ListNode left = dummyleft, right = dummyright; while (head != null) { if (head.val < x) { left.next = head; left = left.next; } else { right.next = head; right = right.next; } head = head.next; } left.next = dummyright.next; right.next = null; return dummyleft.next; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/66204.html
Problem Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings. Example Given intervals = [[0,30],[...
摘要:依然是一道找倒數(shù)第個結(jié)點(diǎn)的鏈表題,用雙指針做。先走,然后和一起走,直到為,的位置就是倒數(shù)第個位置。 Problem Find the nth to last element of a singly linked list. The minimum number of nodes in list is n. Example Given a List 3->2->1->5->null ...
摘要:大體意思就是,先復(fù)制到,順便將所有的放在再復(fù)制所有的到,順便將所有的放在最后令,令,將和分離,返回的頭結(jié)點(diǎn) Problem A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. ...
摘要:而后吾當(dāng)依除取余之法,化大為小,則指針不致于越界也。后欲尋右起第結(jié)點(diǎn),令快指針先行數(shù)日,及至兩指針相距為,便吟鞭東指,與慢指針策馬共進(jìn)。快慢指針亦止于其所焉。舞動長劍,中宮直入,直取首級,而一掌劈空,已鴻飛冥冥。自此,一代天驕,霸業(yè)已成。 Problem Given a list, rotate the list to the right by k places, where k is...
摘要:當(dāng)鏈表為空時,中出現(xiàn)大于,返回。然后計(jì)算中點(diǎn),以為界分別遞歸構(gòu)建左右子樹。順序是,左子樹根結(jié)點(diǎn)右子樹。由于根節(jié)點(diǎn)是直接取構(gòu)建,當(dāng)前的已經(jīng)被取用。所以在下一次遞歸構(gòu)建右子樹之前,要讓指向。最后將和左右子樹相連,返回。 Problem Given a singly linked list where elements are sorted in ascending order, conve...
閱讀 2511·2021-09-26 10:18
閱讀 3386·2021-09-22 10:02
閱讀 3183·2019-08-30 15:44
閱讀 3326·2019-08-30 15:44
閱讀 1831·2019-08-29 15:25
閱讀 2572·2019-08-26 14:04
閱讀 2035·2019-08-26 12:15
閱讀 2437·2019-08-26 11:43