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

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

Leetcode034--將單鏈表進行分區

2019-11-08 03:26:53
字體:
來源:轉載
供稿:網友

一、原題

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. 

一、中文

給定一個單鏈表和一個值x,將鏈表分成小于等于x的部分和大于x的部分。同時保持鏈表原來的相對順序

三、舉例

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

四、思路

 創建兩個鏈表,編譯單鏈表,將鏈表中比較小的元素放到左邊的鏈表中,比較大的放入到右邊的鏈表中

最后將兩個鏈表進行合并就可以了。

五、程序

 
package code;public class LeetCode47{	public static void main(String args[]){		ListNode list1 = new ListNode(1);		ListNode list2 = new ListNode(4);		ListNode list3 = new ListNode(2);		ListNode list4 = new ListNode(2);		ListNode list5 = new ListNode(5);				list1.next = list2;		list2.next = list3;		list3.next = list4;		list4.next = list5;				ListNode list = partition(list1, 3);		while(list != null){			System.out.print(list.val+" ");			list = list.next;		}	}	//將鏈表以x為依據分割開來	public static ListNode partition(ListNode head, int x) {		ListNode left = new ListNode();		ListNode tmpLeft = left;				ListNode right = new ListNode();		ListNode tmpRight = right;				if(head == null || head.next == null){			return head;		}				while(head != null){			if(head.val <= x){				ListNode tmp = new ListNode();				tmp.val = head.val;								left.next = tmp;				left = left.next;			}						if(head.val > x){				ListNode tmp = new ListNode();				tmp.val = head.val;								right.next = tmp;				right = right.next;			}					head = head.next;		}				//將左右兩個鏈表進行連接		left.next = tmpRight.next;				return tmpLeft.next;	}	}	------------------------------------------output-------------------------------------------
1 2 2 4 5
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 绵竹市| 当阳市| 西华县| 汝州市| 印江| 大姚县| 丹江口市| 建湖县| 调兵山市| 留坝县| 托克托县| 夹江县| 石阡县| 山东| 理塘县| 卫辉市| 贵溪市| 连城县| 建宁县| 扬州市| 麻江县| 台山市| 凤城市| 宁夏| 全州县| 南城县| 精河县| 望城县| 信阳市| 定日县| 兴和县| 崇义县| 昆明市| 炉霍县| 南木林县| 彝良县| 河西区| 淮滨县| 广汉市| 铁岭县| 乐安县|