算法系列——Partition List

来源:互联网 发布:雷姆雷姆软件汉化版 编辑:程序博客网 时间:2024/05/16 04:41

题目描述

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.

解题思路

这道题要求将链表分成两个部分,使得所有小于给定值的节点在链表前面,大于等于给定值的节点在链表后面。

采用两个虚拟头结点 ,会使题目非常简单。一节点用来连接小于给定值的部分,另外节点用于连接大于等于给定值的部分,遍历原链表,拿链表中的值和给定值进行比较,按照条件连接到两个虚拟节点尾部即可,最后将这两个链表连接起来。

程序实现

public class Solution {    public ListNode partition(ListNode head, int x) {        if(head==null||head.next==null)            return head;        ListNode dummy1=new ListNode(-1);        ListNode dummy2=new ListNode(-1);        ListNode p1=dummy1;        ListNode p2=dummy2;        ListNode p=head;        while(p!=null){            if(p.val<x){                p1.next=p;                p1=p1.next;            }else{                p2.next=p;                p2=p2.next;            }            p=p.next;        }        p2.next=null;        p1.next=dummy2.next;        return dummy1.next;    }}
原创粉丝点击