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 直接指向了原来的链表。