Middle-题目62：86. Partition List

62人阅读 评论(0)

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.

public class Solution {
public static ListNode partition(ListNode head, int x) {
ListNode beforex = null,afterx = null;
for(ListNode node = head; node!=null; node=node.next) {
if(node.val<x) {
if(beforex == null)
beforex = new ListNode(node.val);
else {
ListNode temp = beforex;
while(temp.next!=null)
temp=temp.next;
temp.next=new ListNode(node.val);
}
}
else {
if(afterx == null)
afterx = new ListNode(node.val);
else {
ListNode temp = afterx;
while(temp.next!=null)
temp=temp.next;
temp.next=new ListNode(node.val);
}
}
}
ListNode temp = beforex;
if (temp!=null) {
while(temp.next!=null)
temp=temp.next;
temp.next=afterx;
return beforex;
}
else
return afterx;
}
}

1ms,beats 4.36%,众数1ms,95.64%
cmershen的碎碎念：

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：63283次
• 积分：3275
• 等级：
• 排名：第10713名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：8条
文章分类
阅读排行
最新评论