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

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

個(gè)人記錄-LeetCode 86. Partition List

2019-11-11 01:55:24
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

問(wèn)題: 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.

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

代碼示例:

/** * 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之前的節(jié)點(diǎn) ListNode prev = null; //otherHead用于記錄另一個(gè)鏈表的頭節(jié)點(diǎn) ListNode otherHead = null; //other用于輪尋另一個(gè)鏈表 ListNode other = null; while (tmp != null) { //小于x的節(jié)點(diǎn)直接跳過(guò) 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加入到另一個(gè)鏈表中 if (other == null) { otherHead = tmp; other = tmp; } else { other.next = tmp; other = other.next; } //繼續(xù)移動(dòng)tmp if (tmp != null) { tmp = tmp.next; } } //合并兩個(gè)鏈表 if (prev != null) { prev.next = otherHead; } else { //這里是原始鏈表中,所有的值都大于等于x的情況 head = otherHead; } return head; }}
發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 准格尔旗| 锦屏县| 广饶县| 南宁市| 黄山市| 金山区| 友谊县| 迁西县| 石屏县| 白山市| 新建县| 甘孜县| 抚宁县| 喀喇沁旗| 望城县| 澳门| 迁西县| 凌云县| 涿州市| 海原县| 志丹县| 米林县| 揭东县| 东明县| 鹤岗市| 定边县| 郓城县| 金川县| 华亭县| 海伦市| 蓝田县| 清涧县| 阿勒泰市| 铁岭县| 石河子市| 永州市| 宾川县| 巴林右旗| 商河县| 江城| 德庆县|