# 【Leetcode】Partition List

263人阅读 评论(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.

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

	public ListNode partition(ListNode head, int x) {
ListNode p = head, h1 = null, r2 = null, r1 = null, h2 = null;
List<Integer> l1 = new ArrayList<Integer>();
List<Integer> l2 = new ArrayList<Integer>();
while (p != null) {
if (p.val < x) {
} else {
}
p = p.next;
}
Iterator<Integer> i1 = l1.iterator();
while (i1.hasNext()) {
if (h1 == null) {
h1 = new ListNode((Integer) i1.next());
r1 = h1;
} else {
r1.next = new ListNode((Integer) i1.next());
r1 = r1.next;
}
}
Iterator<Integer> i2 = l2.iterator();
while (i2.hasNext()) {
if (h2 == null) {
h2 = new ListNode((Integer) i2.next());
r2 = h2;
} else {
r2.next = new ListNode((Integer) i2.next());
r2 = r2.next;
}
}
if (r1 != null) {
r1.next = h2;
} else {
}

}

	public ListNode partition(ListNode head, int x) {
ListNode lessHead = new ListNode(0);
ListNode greaterHead = new ListNode(0);
ListNode node = head, less = lessHead, greater = greaterHead;
while (node != null) {
ListNode next = node.next;
if (node.val < x) {
less.next = node;
less = less.next;
less.next = null;
} else {
greater.next = node;
greater = greater.next;
greater.next = null;
}
node = next;
}
}


0
0

个人资料
• 访问：568257次
• 积分：8668
• 等级：
• 排名：第2676名
• 原创：305篇
• 转载：6篇
• 译文：0篇
• 评论：37条
博客专栏
 Leetcode题解java版 文章：289篇 阅读：490459
文章分类
阅读排行
最新评论