[LeetCode] 86. Partition List Java
生活随笔
收集整理的這篇文章主要介紹了
[LeetCode] 86. Partition List Java
小編覺得挺不錯的,現(xià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.
題意及分析:給出一個鏈表和一個值x,將鏈表中值小于x的點移動到值大于等于x的點之前,分別需要保持保持兩部分中點的相對位置不變。可以分別得到大于等于x的鏈表和小于x的鏈表,然后把兩個鏈表組合起來就是需要的結(jié)果。
代碼:
/*** 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) {ListNode list1=new ListNode(0);ListNode list2=new ListNode(0);ListNode p1=list1;ListNode p2=list2;ListNode start=head;while(start!=null){int value=start.val;if(value<x){p1.next = start;p1=p1.next;// list1.next=null;}else{p2.next = start;p2=p2.next;}start=start.next;}p2.next=null;p1.next=list2.next;return list1.next;} }?
轉(zhuǎn)載于:https://www.cnblogs.com/271934Liao/p/8045988.html
總結(jié)
以上是生活随笔為你收集整理的[LeetCode] 86. Partition List Java的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [linux]centos7下解决yum
- 下一篇: 用老毛桃怎么装win7系统 老毛桃装Wi