wangzheng0822 / algo Goto Github PK
View Code? Open in Web Editor NEW数据结构和算法必知必会的50个代码实现
License: Apache License 2.0
数据结构和算法必知必会的50个代码实现
License: Apache License 2.0
单链表反转,Java实现 LinkedListAlgo.java#L15-L31,可以不需要headNode
,只需返回前一个node即可。
public static Node reverse(Node node) {
Node prev = null;
Node curr = node;
while (curr != null) {
Node next = curr.getNext();
curr.setNext(prev);
prev = curr;
curr = next;
}
return prev;
}
运行后报「Cannot read property 'length' of undefined」错误,没觉得有什么长度 undefined 啊,是什么问题?
insert
a = MyArray(6) # 生成一个capacity为6的array
for i in range(5):
a.insert_to_tail(i)
print(a) # 现在a是 [0, 1, 2, 3, 4]
a.insert(100, 1000) # 在index为100的地方插入1000
这里应该返回False
,插入不成功,但现在的修改导致a
变成了[0, 1, 2, 3, 4, 1000]
。
同样的道理,如果a
现在是[0, 1, 2, 3, 4]
,接下来
a.insert(-1, 1000) # 在倒数第一位插入1000
应该结果为[0, 1, 2, 3, 4, 1000]
,但现在的修改导致a
变成了[1000, 0, 1, 2, 3, 4]
。
print_all
print("{num}", end=" ")
应该是print(f"{num}", end=" ")
.
delete
delete
现在用新的slice去覆盖,这就导致如果对array进行不断删除,再不断添加,等等,它可能不是O(1)。
algo/java/17_skiplist/SkipList.java
Line 47 in ba02e5d
64行
newNode.next = q.next;
此处 newNode的next 是null, q结点循环后next也是null, 这行代码没用吧 ??
`func partition(arr []int, low int, high int) int {
pivot := arr[high]
i := low
for j := low; j < high; j++ {
if arr[j] < pivot {
arr[i], arr[j] = arr[j], arr[i]
i++
}
}
arr[i], arr[high] = arr[high], arr[i]
return i
}
quickSort(arr, start, pivot-1)`
修改以上,可以正确运行 。
While testing the bounds of GenericArray.remove(index) , icondition : index = getCapacity() , throw this exception!!
def reverse(head):
reverse_head = None
current = head
while current:
reverse_head,reverse_head.next,current = current,reverse_head,current.next
为什么
reverse_head = current
reverse_head.next = reverse_head
current = current.next
这样会出错
下面的这个 StackBasedLinkedList 类名是不是应该改为 LinkedListBasedStack?
/**
* 基于链表实现的栈。
*/
public class StackBasedLinkedList
毕竟最终是一个Stack的实现。
比如:"()(()(()))"
按照个人理解:
程序当值相等时只下移current指针,下一个循环且值不相等时,将prev指针的next指针指向current指针,并下移prev指针。
这样刚好单向跳过了需要删除的节点。也就是链里不会再遍历到删除节点。
但是删除的节点的next指针其实还是指在链上,本身节点也没有=None.
这样会不会造成垃圾无法回收?
singly_linked_list.py
def delete_by_value(self, value:int):
if not self._head or not value:
return
fake_head = Node(-1)
fake_head._next = self._head
prev, current = fake_head, self._head
while current:
if current.data != value:
prev._next = current
prev = prev._next
current = current._next
if prev._next:
prev._next = None
self._head = fake_head._next # in case head.data == value
05_array java contains方法可以调用find方法来做判断吧
当链表当中self.__head.next 为None时,while循环调用node.next.data就会出错
`def delete_by_value(self, value):
'''在链表中删除指定存储数据的Node节点.
参数:
value:指定的存储数据
'''
if self.__head == None: # 如果链表是空的,则什么都不做
return
if self.__head.data == value: # 如果链表的头Node节点就是指定删除的Node节点
self.__head = self.__head.next
pro = self.__head
node = self.__head.next
not_found = False
while node.data != value:
if node.next == None: # 如果已经到链表的最后一个节点,则表明该链表中没有找到执行Value值的Node节点
not_found == True
break
else:
pro = node
node = node.next
if not_found == False:
pro.next = node.next
`
`public static Node deleteLastKth(Node list, int k) {
Node fast = list;
int i = 1;
while (fast != null && i < k) {
fast = fast.next;
++i;
}
if (fast == null) return list;
Node slow = list;
Node prev = null;
while (fast.next != null) {
fast = fast.next;
prev = slow;
slow = slow.next;
}
if (prev == null) {
list = list.next;
} else {
prev.next = prev.next.next;
}
return list;
}`
感觉这段代码是删除正序的第k个节点的。不知道我的理解是否正确
def delete(self, index: int) -> bool:
if index >= self._count or index <= -self._count: return False
self._data[index:-1] = self._data[index+1:]
self._count -= 1
return True
这里delete虽然有移位,但是最后一个元素没有删除, 那就会引起删除之后insert失败的效果
i.e.
a = MyArray(6)
for i in range(6):
a.insert_to_tail(i)
print(a)
out: 0 1 2 3 4 5
a.delete(2)
print(a)
out: 0 1 3 4 5 ---> "其实索引为5的值还是5,只是没有显示"
a.insert_to_tail(7)
print(a)
out: 0 1 3 4 5 5 ---> "这里就出现了问题了"
listNode *mergeTwoLists(listNode *l1,listNode *l2)
{
listNode head = {0};
listNode *pRes = &head;
while(1)
{
if(l1 == NULL)
{
pRes->next = l2;
}
if (l2 == NULL)
{
pRes->next = l1;
}
if(l1->val < l2->val)
{
pRes->next = l1;
l1 = l1->next;
}
else
{
pRes->next = l2;
l2 = l2->next;
}
pRes = pRes->next;
}
return head;
}
这个不是个死循环吗,怎么退出,怎么觉得写的很草率。
代码无法实现排序
我觉得得dequeue似乎有点问题,出队列的话,是不是应该把那个head的元素置空啊?
public String dequeue() {
if (tail == head) {
return null;
}
String item=items[head];
items[head]=null;
head=(head+1)%capacity;
return item;
}
//删除节点
func (sl *SkipList) Delete(v interface{}, score int) int {
if nil == v {
return 1
}
//查找前驱节点
cur := sl.head
//记录前驱路径
update := [MAX_LEVEL]*skipListNode{}
for i := sl.level - 1; i >= 0; i-- {
update[i] = sl.head
for nil != cur.forwards[i] {
//缺少判断
if cur.forwards[i].score > score{
break
}
if cur.forwards[i].score == score && cur.forwards[i].v == v {
update[i] = cur
break
}
cur = cur.forwards[i]
}
}
cur = update[0].forwards[0]
for i := cur.level - 1; i >= 0; i-- {
if update[i] == sl.head && cur.forwards[i] == nil {
sl.level = i
}
if nil == update[i].forwards[i] {
update[i].forwards[i] = nil
} else {
update[i].forwards[i] = update[i].forwards[i].forwards[i]
}
}
sl.length--
return 0
}
单链表java代码中的
public void deleteByNode(Node p) {
if (p == null || head == null) return;
if (p == head) {
head = head.next;
return;
}
Node q = head;
while (q != null && q.next != p) {
q = q.next;
}
if (q == null) {
return;
}
q.next = q.next.next;
}
如果长度为1的话q.next是不是遍历不到???
def delete_by_node(self, node: Node):
if not self._head or not node:
return
if node._next: #这个是用来干嘛的,实在没搞懂
node.data = node._next.data
node._next = node._next._next
return
current = self._head
while current and current._next != node:
current = current._next
if not current:
return
current._next = node._next
def delete_by_value(self, value: int):
if not self._head or not value:
return
fake_head = Node(value + 1)
fake_head.next = self._head
prev, current = fake_head, self._head
while current: #没有停止的条件?什么时候停止?
if current.data != value:
prev._next = current
prev = prev._next
current = current._next
if prev._next:
prev._next = None
self._head = fake_head._next
if node._next: #这个是用来干嘛的,实在没搞懂
node.data = node._next.data
node._next = node._next._next
return
while current: #没有停止的条件?什么时候停止?这里主要是用来做什么的?
if current.data != value:
prev._next = current
prev = prev._next
current = current._next
小白求指教!
在反转的时候 新的头节点(tmp)没有初始化,导致在反转后dump时 会出错 初始化后就可以修复了
``
// 获取对应 index 位置的元素
public T get(int index) {
checkIndex(index);
return data[index];
}
private void checkIndex(int index) {
if(index < 0 || index > size) {
throw new IllegalArgumentException("Add failed! Require index >=0 and index <= size.");
}
}
``
if (index<0 || index>=count) return false;
刚开始插入元素的时候, index >= count 就会出问题,因为 count 初始化为 0,所以即使从头开始插入(即 index = 0),也插入不成功。换句话说根本插入不了元素,我觉得应该改成将 index >= count 改成 index > count:
if (index<0 || index > count) return false;
不知道理解对不对。
文章的图都很直观与美观,老师是怎么做的,谢谢了。
Line 56 in 5ebfdc9
index != this.length 插入时候我理解应该是任意位置,插入的索引位置可以和长度不相等,不知道是不是我理解有问题
为什么没有实现48课时的B+tree呢,想看一下落盘问题是怎么解决的?
会报空指针,我改成这样子,应该还会有更好的方法 while (head != null && head.data == value) { head = head.next; } Node pNode = head; while (pNode != null && pNode.next != null) { if (pNode.next.data == value) { pNode.next = pNode.next.next; continue; } pNode = pNode.next; }
估计是没有理解到位,合并后不是有序的。两个有序的链表合并,当然要求合并完还是有序的。
$arrLen = count($operStack);
while ($operStack[$arrLen-1] === '/'){
compute($numStack, $operStack);
$arrLen--;
}
array_push($operStack, $arr[$i]);
break;
upstream/master
case '/':
调试环境:Chrome控制台
报错内容:Uncaught RangeError: Maximum call stack size exceeded
复现方式:将仓库中的JS版本快速排序代码在Chrome控制台进行调试,当数组长度为100万的时候,会出现超出最大调用次数的报错。
请问这个是什么原因造成的呢?
public bool Delete(T val)
{
int index = IndexOf(val);
if(index == -1)
{
return false;
}
return Delete(index);
}
这样写应该更准确些
`
// 单链表反转
public static Node reverse(Node list) {
Node headNode = null;
Node previousNode = null;
Node currentNode = list;
while (currentNode != null) {
Node nextNode = currentNode.next;
if (nextNode == null) {
headNode = currentNode;
}
currentNode.next = previousNode;
previousNode = currentNode;
currentNode = nextNode;
}
return headNode;
}`
将while 循环中的if判断去了 再循环接受后再改变headNode是否会更优?
改为:
`
// 单链表反转
public static Node reverse(Node list) {
Node headNode = null;
Node previousNode = null;
Node currentNode = list;
while (currentNode != null) {
Node nextNode = currentNode.next;
currentNode.next = previousNode;
previousNode = currentNode;
currentNode = nextNode;
}
headNode = previousNode;
return headNode;
}`
换个数据,示例的排序会出错
function insertSort(&$data)
{
$length = count($data);
for ($i = 1; $i < $length; $i++) {
$temp = $data[$i];
for ($j = $i; $j > 0; $j--) {
if ($data[$j - 1] > $temp) {
$data[$j] = $data[$j - 1];
} else {
break;
}
}
$data[$j] = $temp;
}
}
$arr = [4, 5, 6, 1, 3, 2];
insertSort($arr);
print_r($arr);
测试不出来结果,请问有人运行成功么,我全是失败
05_array/GenericArray.java
public void set(int index, T e) {
// 此处调用checkIndex检查索引,修改值时索引应大于0或小于数组元素个数吧?
// 是否应改成index < 0 || index >= size
checkIndex(index);
data[index] = e;
}
private void checkIndex(int index) {
if (index < 0 || index > size) {
throw new IllegalArgumentException("Add failed! Require index >=0 and index <= size.");
}
这里在回文串的实现有问题,在
leftLink = inverseLinkList(p);
System.out.println("左边第一个节点"+leftLink.data);
System.out.println("右边第一个节点"+p.next.data);
rightLink = p;
这段代码中leftLink和rightLink实际指向的是同一个引用,你反转时对p进行了操作,同样会影响到rightLink,实际你现在leftLink和 rightLink存放的都是左半部分的链表数据,判断回文串时永远会是true!
问题:
https://github.com/wangzheng0822/algo/blob/master/javascript/07_linkedlist/LinkedListAlgo.js
第29行的 findByIndex(index) 方法
// 根据index查找节点
findByIndex(index) {
let currentNode = this.head
...
...
return currentNode === null ? -1 : pos
}
不应返回pos,而是所找节点
解决:
return currentNode === null ? -1 : currentNode
func (this *Array) isIndexOutOfRange(index uint) bool {
if this.length != 0 && index > this.length {
return true
}
return false
}
假如这里是数组length是3,如果取index==3的数值也应该是越界,这样理解的话index > this.length
应该改为index >= this.length
During deletion, levelCount is not adjusted.
// 取p到r之间的中间位置q,防止(p+r)的和超过int类型最大值
int q = p + (r - p)/2;
这也太牛逼了吧,这都想的到!!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.