链表算法题
//Node 定义
public static class Node {
//值
public int value;
//下一个节点
public Node next;
public Node(int v) {
value = v;
}
快慢指针
1.奇数长度返回中点,偶数长度返回上中点
public static Node midOrUpMidNode(Node head) {
//本身head为null,含有0个,1个节点--这些边界情况
if (head == null || head.next == null || head.next.next == null) {
return head;
}
//slow指向第一个节点
Node slow = head.next;
//fast指向第二个节点
Node fast = head.next.next;
while (fast.next != null && fast.next.next != null) {
//slow走一个,fast走两个
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
2.奇数长度返回中点,偶数长度返回下中点
public static Node midOrDownMidNode(Node head) {
//0个节点
if (head == null || head.next == null) {
return head;
}
//slow与fast均指向第一个节点
Node slow = head.next;
Node fast = head.next;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
3.将单链表划分为左边小于某值 中间与某值相等 右边大于某值
把链表放入数组,然后用partition
public static Node listPartition1(Node head, int pivot) {
if (head == null) {
return head;
}
//为了求得i,申请多大的空间
Node cur = head;
int i = 0;
while (cur != null) {
i++;
cur = cur.next;
}
//申请数组
Node[] nodeArr = new Node[i];
i = 0;
cur = head;
for (i = 0; i != nodeArr.length; i++) {
nodeArr[i] = cur;
cur = cur.next;
}
arrPartition(nodeArr, pivot);
for (i = 1; i != nodeArr.length; i++) {
nodeArr[i - 1].next = nodeArr[i];
}
nodeArr[i - 1].next = null;
return nodeArr[0];
}
public static void arrPartition(Node[] nodeArr, int pivot) {
int small = -1;
int big = nodeArr.length;
int index = 0;
while (index != big) {
if (nodeArr[index].value < pivot) {
swap(nodeArr, ++small, index++);
} else if (nodeArr[index].value == pivot) {
index++;
} else {
swap(nodeArr, --big, index);
}
}
}