链表分割

题目要求

编写代码,以给定值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中的内存回收可以解决,不过应该考虑更好的方法解决该问题。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值