分割原来的链表

18 篇文章 0 订阅
该文章介绍了一个Java代码实现,用于对链表进行操作,将所有值小于等于X的节点移动到链表的前面,同时保持原有节点的相对顺序。通过创建两个辅助链表,分别存储小于等于X和大于X的节点,然后合并这两个链表来完成排序。
摘要由CSDN通过智能技术生成

1.题目

现有一个链表,给定一个X值,将小于等于X的节点排在链表的前面,且不改变原来的相对顺序。

2.分析

设置两个链表,一个链表小于等于X,一个链表大于X。

遍历所给的链表,分别放入两个链表中;

链接两个链表。

3.代码

/**
 * Describe:现有一个链表,给定一个X值,将小于等于X的节点排在链表的前面,且不改变原来的相对顺序。
 * User:lenovo
 * Date:2023-01-06
 * Time:14:14
 */



class Node {
    int val;
    Node next;

    public Node() {

    }
    public Node(int val) {
        this.val = val;
    }
}
class MyLinkedList {
    public Node head;

    public MyLinkedList(Node head) {
        this.head = head;
    }
    public MyLinkedList() {
    }
}
public class Test {
    public static MyLinkedList split(MyLinkedList list, int x){
        //链表为空
        if(list == null) {
            return null;
        }
        Node headA = new Node();
        Node headB = new Node();
        Node curA = headA;
        Node curB = headB;
        Node cur = list.head;
        //比较大小
        while(cur != null) {
            if(cur.val <= x) {
                curA.next = cur;
                curA = curA.next;
            }else {
                curB.next = cur;
                curB = curB.next;
            }
            cur = cur.next;
        }
        //链接两个链表
        curA.next = headB.next;
        MyLinkedList newlist = new MyLinkedList(headA.next);
        return newlist;
    }
    public static void main(String[] args) {
        Node n1 = new Node(5);
        Node n2 = new Node(8);
        Node n3 = new Node(10);
        Node n4 = new Node(1);
        Node n5 = new Node(16);
        Node n6 = new Node(20);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        n5.next = n6;
        MyLinkedList myLinkedList = new MyLinkedList(n1);
        Node cur = split(myLinkedList, 10).head;
        while(cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();


    }
}
  • 判断链表为空,直接返回空;

  • 与X比较大小,放在相应的链表中;

  • 链接两个链表

4.总结

列举在实现的过程中可能出现的错误,如:

与X比较大小时(即循环体)

我们这样写是错误的,我们并没有在headA或headB的基础上进行链接,而是直接让curA或curB 直接指向了原来的链表。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值