Java 围绕整数值对链表进行分区
我正试图编写代码,将一个链表围绕一个值x进行分区,这样所有小于x的节点都位于所有大于或等于x的节点之前。如果x包含在列表中,则x的值必须位于小于x的元素之后。但是,分区元素x可以出现在“右分区”中的任何位置 输入3->5->8->5->10->2->1[分区=5] 输出3->1->2->10->5->5->8 节点类的定义如下Java 围绕整数值对链表进行分区,java,algorithm,linked-list,Java,Algorithm,Linked List,我正试图编写代码,将一个链表围绕一个值x进行分区,这样所有小于x的节点都位于所有大于或等于x的节点之前。如果x包含在列表中,则x的值必须位于小于x的元素之后。但是,分区元素x可以出现在“右分区”中的任何位置 输入3->5->8->5->10->2->1[分区=5] 输出3->1->2->10->5->5->8 节点类的定义如下 class Node{ Node next = null; int data; public Node(int d){ data
class Node{
Node next = null;
int data;
public Node(int d){
data =d;
}
public Node() {
// TODO Auto-generated constructor stub
}
void appendToTail(int d){
Node end = new Node(d);
Node n = this;
while(n.next!=null){
n = n.next;
}
n.next = end;
}
下面是我提出的半工作代码
static void Partition(Node n,int numb){
Node tail = n;
while(tail.next != null){
tail = tail.next;
}
Node current = n;
Node tailCurrent = tail;
Node prev = null;
while(current!= tailCurrent){
if(current.data<numb){
prev = current;
System.out.println(prev.data);
}
else{
prev.next = current.next;
tail.next = current;
tail = current;
}
current =current.next;
}
tail.next = null;
}
静态无效分区(节点n,int numb){
节点尾=n;
while(tail.next!=null){
tail=tail.next;
}
节点电流=n;
节点尾流=尾流;
Node prev=null;
while(当前!=尾流){
如果(current.data没有要更新的前一个节点,那么您可以什么也不做
因此,改变这一点:
prev.next = current.next;
为此:
if (prev != null) {
prev.next = current.next;
}
还有另一个问题:列表的根在分区过程中可能会发生变化,调用代码无法访问新的根。可以通过让分区
方法跟踪当前根所在的位置并最终返回来解决
static Node Partition(Node n, int numb) {
Node tail = n;
while(tail.next != null) {
tail = tail.next;
}
Node current = n;
Node root = n;
Node tailCurrent = tail;
Node prev = null;
while(current != tailCurrent) {
if(current.data < numb) {
prev = current;
} else {
if (prev != null) {
prev.next = current.next;
}
if (root == current) {
root = current.next;
}
tail.next = current;
tail = current;
}
current = current.next;
}
tail.next = null;
return root;
}
静态节点分区(节点n,int numb){
节点尾=n;
while(tail.next!=null){
tail=tail.next;
}
节点电流=n;
节点根=n;
节点尾流=尾流;
Node prev=null;
while(当前!=尾流){
如果(当前数据
我不理解这一部分:但是,分区元素x可以出现在“右分区”中的任何位置。您能再举几个例子吗?