大家好,都吃晚饭了吗?我是Kaiqisan,是一个已经走出社恐的一般生徒,今天再来康康链表的算法
问题
荷兰国旗问题 — 给一串链表,再给一个数字,让做左部分的值比这个数字小,右部分的值比这个数字大,且不修改它们的相对位置。
比如
flag = 3
3 -> 2 -> 1 -> 5 -> 6 -> 7 -> 4
变换后
2 -> 1 -> 3 -> 5 -> 6 -> 7 -> 4
进阶要求:时间复杂度 O(N) 空间复杂度O(1)
暗示不能使用额外空间创建链表
解答
思路,先遍历第一遍链表,找第一个比参考值小的点和第一个比参考值大的点和第一个等于参考值的节点,有就尽量找,没有就放弃不强求,(起码可以找到一个
找到之后再次遍历链表,比较当前的值和参考值,然后再进行如下连接(不使用上面的案例)
然后把Less Equal More 依次链接起来
// 第一个参数为输入的链表,第二个参数为判定值
static LinkList exeSort(LinkList head, int judgeVal) {
LinkList Less = null;
LinkList Equal = null;
LinkList More = null;
// 头
LinkList _Less = null;
LinkList _Equal = null;
LinkList _More = null;
LinkList _head = head;
while (_head != null) {
if (_head.val > judgeVal && More == null) {
More = _head;
_More = More;
}
if (_head.val < judgeVal && Less == null) {
Less = _head;
_Less = Less;
}
if (_head.val == judgeVal && Equal == null) {
Equal = _head;
_Equal = Equal;
}
_head = _head.next;
}
_head = head;
LinkList temp;
while (_head != null) {
temp = _head;
_head = _head.next;
if (temp.val > judgeVal && temp != More) {
More.next = temp;
More = More.next;
} else if (temp.val < judgeVal && temp != Less) {
Less.next = temp;
Less = Less.next;
} else if (temp.val == judgeVal && temp != Equal) {
Equal.next = temp;
Equal = Equal.next;
}
temp.next = null;
}
LinkList a = new LinkList(0);
LinkList _a = a;
if (Less != null) {
a.next = _Less;
a = doRead(a);
}
if (Equal != null) {
a.next = _Equal;
a = doRead(a);
}
if (More != null) {
a.next = _More;
}
return _a.next;
}
总结
链表中的命名可能要起得尽量普通些,因为如果您要追求极致的内存空间的话,需要找到前面已经使用完成的变量,实现“废物利用”。如果您的名字起得太有目的性的话在后面的使用中容易产生理解上的困难。