TypeScript算法题实战——剑指 Offer篇
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
以下是一个简化的代码实例,展示了如何使用 TypeScript 来解决剑指 Offer 题目中的“逆序打印链表”问题:
// 定义链表节点类型
class ListNode {
val: number;
next: ListNode | null;
constructor(val?: number, next?: ListNode | null) {
this.val = (val===undefined ? 0 : val)
this.next = (next===undefined ? null : next)
}
}
// 逆序打印链表的函数
function reversePrint(head: ListNode | null): number[] {
const result: number[] = [];
let current = head;
while (current != null) {
result.push(current.val);
current = current.next;
}
return result.reverse();
}
// 示例使用
const head = new ListNode(1, new ListNode(3, new ListNode(2, new ListNode(4, new ListNode(5, null)))));
console.log(reversePrint(head)); // 输出: [5, 4, 3, 2, 1]
这段代码首先定义了一个链表节点类型ListNode
,然后实现了reversePrint
函数,该函数通过遍历链表并收集每个节点的值,最后返回的数组通过调用reverse
方法进行了逆序。最后,我们创建了一个示例链表并调用reversePrint
函数,输出其逆序打印的结果。
评论已关闭