题目要求
编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前
给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。
思路解析
首先构建链表,然后添加节点,再将所构成的链表以x值分为大小两个部分,最后将新的两个链表连接起来。
代码如下
public class MySingleList{
class Node {
private int data;
public Node next;
public Node(int data) {
this.data = data;
}
public int getData() {
return data;
}
public Node getNext() {
return next;
}
}
private Node head;
public Node getHead() {
return head;
}
public MySingleList(){
this.head = null;
}
public void addFirst(int data) {
Node node = new Node(data);
//第一次插入的时候,没有任何的数据节点
if(this.head == null) {
this.head = node;
}else {
node.next = this.head;
this.head = node;
}
}
public Node partition(Node pHead, int x) {
Node cur = pHead;
Node Shead = new Node(-1);
Node Bhead = new Node(-1);
Node ca = Shead;
Node ba = Bhead;
Node head = null;
while(cur != null){
if(cur.data < x){
ca.next = cur;
ca = ca.next;
}else {
ba.next =cur;
ba = ba.next;
}
cur = cur.next;
}
cur = Shead;
while(cur != null){
cur = cur.next;
}
ca.next = Bhead.next;
return Shead.next;
}
}
总结
本题中新建了节点,浪费了许多内存,不过JAVA中的内存回收可以解决,不过应该考虑更好的方法解决该问题。