86. Partition List

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小的放入headA,其余放入headB,最后把两个链表接起来。 要注意把右侧链表的下一节点设置为null。

Time Complexity - O(n), Space Complexity - O(1)

/**
 * 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) {
        if(head == null || head.next == null)
            return head;
        ListNode headLeft = new ListNode(-1);
        ListNode headRight = new ListNode(-1);
        ListNode nodeLeft = headLeft;
        ListNode nodeRight = headRight;
        
        while(head != null){
            if(head.val < x){
                nodeLeft.next = head;
                nodeLeft = nodeLeft.next;
            } else {
                nodeRight.next = head;
                nodeRight = nodeRight.next;
            }
                
            head = head.next;
        }
        
        nodeRight.next = null;
        nodeLeft.next = headRight.next;
        return headLeft.next;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Given a linked list and a value x, partition it such that...
    BeijingIamback阅读 415评论 0 0
  • 昆仑山地处西北边陲,距离遥远,拜师昆仑的玩家并不多。据官网统计,仅有1%多一点的玩家选择了昆仑派拜师,远远...
    高等巫妖阅读 311评论 0 0
  • 昏黄的灯光,朦胧又缱绻。 鱼尾藤饰,旧色新器,素雅浅淡,独透一份辉色。已无从追溯本源。 听雨,点点滴滴,在阶前、檐...
    阿蜜又尔阅读 115评论 0 0
  • 点击这里查看《我不勇敢》完整故事 第四章 全心全意等待着你说愿意 (四) 四道口的房子已经住了三个月,需要交下季度...
    孟小北阅读 486评论 0 0
  • 很多时候,我们都会陷入一种无意识的思维,先下结论,然后寻找论据来证明自己的结论有多么的正确。 如果你第一眼看一个人...
    投资进化营阅读 766评论 0 3