Java 链表分区稳定性说明?
我一直在研究CTCI,遇到了一个关于链表的问题: '给定一个链表和一个值x,将链表围绕一个值x进行分区,使小于x的所有节点位于大于或等于x的所有节点之前。如果x包含在列表中,则x的值只需位于小于x的元素之后(见下文)。分区元素x可以出现在“右分区”中的任何位置;它不需要出现在左分区和右分区之间,例如Java 链表分区稳定性说明?,java,data-structures,linked-list,Java,Data Structures,Linked List,我一直在研究CTCI,遇到了一个关于链表的问题: '给定一个链表和一个值x,将链表围绕一个值x进行分区,使小于x的所有节点位于大于或等于x的所有节点之前。如果x包含在列表中,则x的值只需位于小于x的元素之后(见下文)。分区元素x可以出现在“右分区”中的任何位置;它不需要出现在左分区和右分区之间,例如 Input : 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1 x = 5 Output : 3-> 1->
Input : 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1
x = 5
Output : 3-> 1-> 2-> 5-> 8-> 5-> 10
如果我们不想让列表中的元素变得“稳定”,那么我所看到的解决方案是可行的,但我对此感到有点困惑。如果说稳定性,它意味着:
'具有相等或相同键的两个对象在排序输出中的显示顺序与它们在要排序的输入中的显示顺序相同'
那么我相信下面的代码实现了这一点?下面的代码怎么不稳定?谢谢
public class Partition {
/* Link list Node */
static class Node {
int data;
Node next;
}
// A utility function to create a new node
static Node newNode(int data) {
Node new_node = new Node();
new_node.data = data;
new_node.next = null;
return new_node;
}
/* Not stable? Breaks original order or referring to memory? */
static Node partition(Node node, int x) {
Node head = node;
Node tail = node;
while (node != null){
Node next = node.next;
if (node.data < x){
node.next = head;
head = node;
}
else {
tail.next = node;
tail = node;
}
node = next;
}
tail.next = null;
return head;
}
/* Function to print linked list */
static void printList(Node head)
{
Node temp = head;
while (temp != null)
{
System.out.print(temp.data + " ");
temp = temp.next;
}
}
public static void main(String []args){
/* Start with the empty list */
Node head = newNode(3);
head.next = newNode(5);
head.next.next = newNode(8);
head.next.next.next = newNode(5);
head.next.next.next.next = newNode(10);
head.next.next.next.next.next = newNode(2);
head.next.next.next.next.next.next = newNode(1);
int x = 5;
head = partition(head, x);
printList(head);
}
}
公共类分区{
/*链接列表节点*/
静态类节点{
int数据;
节点下一步;
}
//用于创建新节点的实用程序函数
静态节点newNode(int数据){
Node new_Node=新节点();
new_node.data=数据;
new_node.next=null;
返回新的_节点;
}
/*不稳定?破坏原始顺序或引用内存*/
静态节点分区(节点节点,int x){
节点头=节点;
节点尾=节点;
while(节点!=null){
Node next=Node.next;
if(node.data
“稳定性”在这种情况下意味着所有