gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
使用typescript写一个双向链表
- User
使用typescript写一个双向链表
- Assistant
可以使用如下的typescript代码实现一个双向链表:
class ListNode<T> { public prev: ListNode<T> | null; public next: ListNode<T> | null; constructor(public value: T) { this.prev = null; this.next = null; } } class DoublyLinkedList<T> { private head: ListNode<T> | null; private tail: ListNode<T> | null; private length: number; constructor() { this.head = null; this.tail = null; this.length = 0; } public get(index: number): T | undefined { if (index < 0 || index >= this.length) { return undefined; } let current: ListNode<T> | null; if (index <= this.length / 2) { current = this.head; for (let i = 0; i < index; i++) { current = current!.next; } } else { current = this.tail; for (let i = this.length - 1; i > index; i--) { current = current!.prev; } } return current!.value; } public push(value: T): number { const node = new ListNode(value); if (this.length === 0) { this.head = node; this.tail = node; } else { node.prev = this.tail; this.tail!.next = node; this.tail = node; } this.length++; return this.length; } public pop(): T | undefined { if (this.length === 0) { return undefined; } const node = this.tail; if (this.length === 1) { this.head = null; this.tail = null; } else { this.tail = node!.prev; this.tail!.next = null; node!.prev = null; } this.length--; return node!.value; } public unshift(value: T): number { const node = new ListNode(value); if (this.length === 0) { this.head = node; this.tail = node; } else { node.next = this.head; this.head!.prev = node; this.head = node; } this.length++; return this.length; } public shift(): T | undefined { if (this.length === 0) { return undefined; } const node = this.head; if (this.length === 1) { this.head = null; this.tail = null; } else { this.head = node!.next; this.head!.prev = null; node!.next = null; } this.length--; return node!.value; } } - User
添加push_front函数
- Assistant
可以在
DoublyLinkedList类中添加一个pushFront()函数来实现在链表开头插入新元素的功能。class ListNode<T> { public prev: ListNode<T> | null; public next: ListNode<T> | null; constructor(public value: T) { this.prev = null; this.next = null; } } class DoublyLinkedList<T> { private head: ListNode<T> | null; private tail: ListNode<T> | null; private length: number; constructor() { this.head = null; this.tail = null; this.length = 0; } // 省略 get、push、pop、shift 方法的实现 public pushFront(value: T): number { const node = new ListNode(value); if (this.length === 0) { this.head = node; this.tail = node; } else { node.next = this.head; this.head!.prev = node; this.head = node; } this.length++; return this.length; } }pushFront()函数的实现与unshift()类似,只是为了符合语义,修改了函数名。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.