国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

個人記錄-LeetCode 86. Partition List

2019-11-11 00:30:16
字體:
來源:轉載
供稿:網友

問題: 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.

For example, Given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5.

這個問題的思路是:輪尋整個鏈表,將大于等于x的node移到另一個鏈表中。 然后,合并兩個鏈表即可。

代碼示例:

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode partition(ListNode head, int x) { //tmp用于輪尋原始鏈表 ListNode tmp = head; //prev用于記錄tmp之前的節點 ListNode prev = null; //otherHead用于記錄另一個鏈表的頭節點 ListNode otherHead = null; //other用于輪尋另一個鏈表 ListNode other = null; while (tmp != null) { //小于x的節點直接跳過 while (tmp != null && tmp.val < x) { prev = tmp; tmp = tmp.next; } //否則將tmp從原始鏈表中移除 if (tmp != null) { if (prev != null) { prev.next = tmp.next; } else { head = tmp.next; } } //將tmp加入到另一個鏈表中 if (other == null) { otherHead = tmp; other = tmp; } else { other.next = tmp; other = other.next; } //繼續移動tmp if (tmp != null) { tmp = tmp.next; } } //合并兩個鏈表 if (prev != null) { prev.next = otherHead; } else { //這里是原始鏈表中,所有的值都大于等于x的情況 head = otherHead; } return head; }}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 仙居县| 大竹县| 新竹县| 海阳市| 吴旗县| 滨州市| 资溪县| 任丘市| 蚌埠市| 咸阳市| 怀柔区| 日照市| 澄迈县| 信阳市| 樟树市| 宾阳县| 龙里县| 临桂县| 绥化市| 清原| 电白县| 游戏| 如东县| 隆尧县| 泾川县| 福鼎市| 平塘县| 屯昌县| 鹿邑县| 荥阳市| 张家界市| 湖北省| 遂平县| 宁陵县| 庄河市| 石景山区| 怀仁县| 徐汇区| 福建省| 烟台市| 东乌珠穆沁旗|