摘要:新建两个链表,分别存和的结点。令头结点分别叫作和,对应的指针分别叫作和。然后遍历,当小于的时候放入,否则放入。最后,让较小值链表尾结点指向较大值链表头结点,再让较大值链表尾结点指向。
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; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/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...
阅读 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