如何查看完整LinkedList?基于LinkedList实现Queue的问题
如何查看LinkedList实现的Queue的完整链表链?
问题背景
用链表实现Queue的代码如下:
class ListNode { constructor(x) { this.value = x; this.next = null; } } class Queue { constructor() { this.first = null this.last = null this.length = 0 } getUnderlyingList() { return this.first } enqueue(value) { const newNode = new ListNode(value); if (this.isEmpty()) { this.first = newNode; this.last = newNode; } else { this.last.next = newNode; this.last = newNode; } this.length++; return this ; } dequeue() { if (this.isEmpty()) return null; const itemToDel = this.first; if (this.first === this.last) { this.last = null; } this.first = this.first.next; this.length--; return itemToDel; } }
调用getUnderlyingList()期望返回完整链表结构:
{"value":537,"next":{"value":201,"next":{"value":886,"next":{"value":582,"next":{"value":518,"next":{"value":42,"next":{"value":668,"next":{"value":48,"next":{"value":136,"next":{"value":674,"next":null}}}}}}}}}
但实际仅返回:
{"value":674,"next":null}
问题原因
大概率是你的Queue实例状态异常:
- 可能在调用
getUnderlyingList()前,执行了多次dequeue操作,导致this.first指针移动到了链表的最后一个节点(比如入队10个元素后出队9次,first就会指向第10个元素)。 - 也可能是入队顺序错误,把674作为第一个元素入队,后续元素未正确挂载(但从代码看
enqueue逻辑是正确的,这种概率较低)。
解决方法
1. 先验证Queue的状态
在调用getUnderlyingList()前,先打印Queue的核心属性,确认first是否指向链表头节点:
const queue = new Queue(); // 执行入队操作: queue.enqueue(537); queue.enqueue(201); queue.enqueue(886); // ... 其他元素依次入队 queue.enqueue(674); // 验证状态 console.log('头节点值:', queue.first.value); // 应为537 console.log('尾节点值:', queue.last.value); // 应为674 console.log('队列长度:', queue.length); // 应为10
如果first.value不是537,说明你之前的dequeue操作过多,或者入队逻辑被意外修改。
2. 手动遍历链表生成完整结构
如果需要确保能输出完整的链表链,可以实现一个序列化函数,从任意节点开始遍历并生成完整的链式结构:
function serializeLinkedList(head) { let current = head; const serialized = []; // 先收集所有节点的value while (current) { serialized.push({ value: current.value }); current = current.next; } // 反向构建next引用 for (let i = serialized.length - 2; i >= 0; i--) { serialized[i].next = serialized[i + 1]; } return serialized[0] || null; } // 使用示例 const fullLinkedList = serializeLinkedList(queue.getUnderlyingList()); console.log(JSON.stringify(fullLinkedList));
这个函数会从传入的头节点开始,遍历整个链表,生成符合你期望的完整链式JSON结构。
3. 直接生成JSON字符串(更高效)
如果不想生成中间对象,也可以直接遍历生成目标JSON字符串:
function stringifyLinkedList(head) { if (!head) return 'null'; let str = ''; let current = head; while (current) { str += `{"value":${current.value},"next":`; current = current.next; } str += 'null'; // 补充闭合括号 str += '}'.repeat(head ? queue.length : 0); return str; } // 使用示例 console.log(stringifyLinkedList(queue.getUnderlyingList()));
内容的提问来源于stack exchange,提问作者Боржч
相关产品推荐
相关产品推荐

