【发布时间】:2016-05-06 15:54:12
【问题描述】:
我正在尝试基于链表数据结构解决这个算法问题。问题如下:
给定一个链表和一个值 x,对它进行分区,使得所有小于 x 的节点都在大于或等于 x 的节点之前。 您应该保留两个分区中每个分区中节点的原始相对顺序。
例如,
给定 1->4->3->2->5->2 和 x = 3, 返回 1->2->2->4->3->5.
我的解决方法是:
/**
* 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) return null;
ListNode headNode = new ListNode(-1);
headNode.next = head;
ListNode tail = head;
while(tail.next!=null){
tail = tail.next;
}
ListNode actualTail = tail;
ListNode current = headNode;
while(current!=actualTail && current.next!=actualTail){
if(current.next.val >= x && current.next!=tail){
System.out.println("Moving "+current.next.val+" to end of list, ahead of "+tail.val);
ListNode temp = current.next;
current.next = current.next.next;
tail.next = temp;
tail = tail.next;
tail.next = null;
}else{
current = current.next;
}
}
return headNode.next;
}
}
虽然某些测试用例可以很好地使用上面提到的代码,但有一组测试用例失败了,因为我无法保持列表中节点的原始相对顺序。
例如: 列表 = [1->2] x = 0
我的结果: [2,1]
预期: [1,2]
任何帮助将不胜感激。
【问题讨论】:
-
所有小于 x 的节点都在大于或等于 x 的节点之前。还要保留原来的相对顺序。
标签: algorithm data-structures linked-list