摘要:新建兩個鏈表,分別存和的結點。令頭結點分別叫作和,對應的指針分別叫作和。然后遍歷,當小于的時候放入,否則放入。最后,讓較小值鏈表尾結點指向較大值鏈表頭結點,再讓較大值鏈表尾結點指向。
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; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://m.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],[...
摘要:依然是一道找倒數第個結點的鏈表題,用雙指針做。先走,然后和一起走,直到為,的位置就是倒數第個位置。 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 ...
摘要:大體意思就是,先復制到,順便將所有的放在再復制所有的到,順便將所有的放在最后令,令,將和分離,返回的頭結點 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. ...
摘要:而后吾當依除取余之法,化大為小,則指針不致于越界也。后欲尋右起第結點,令快指針先行數日,及至兩指針相距為,便吟鞭東指,與慢指針策馬共進。快慢指針亦止于其所焉。舞動長劍,中宮直入,直取首級,而一掌劈空,已鴻飛冥冥。自此,一代天驕,霸業已成。 Problem Given a list, rotate the list to the right by k places, where k is...
摘要:當鏈表為空時,中出現大于,返回。然后計算中點,以為界分別遞歸構建左右子樹。順序是,左子樹根結點右子樹。由于根節點是直接取構建,當前的已經被取用。所以在下一次遞歸構建右子樹之前,要讓指向。最后將和左右子樹相連,返回。 Problem Given a singly linked list where elements are sorted in ascending order, conve...
閱讀 2520·2021-09-26 10:18
閱讀 3397·2021-09-22 10:02
閱讀 3196·2019-08-30 15:44
閱讀 3333·2019-08-30 15:44
閱讀 1838·2019-08-29 15:25
閱讀 2581·2019-08-26 14:04
閱讀 2047·2019-08-26 12:15
閱讀 2446·2019-08-26 11:43