Skip to content

Commit ea2fdd8

Browse files
committed
添加链表单元测试
1 parent 2e1cffc commit ea2fdd8

File tree

2 files changed

+33
-14
lines changed

2 files changed

+33
-14
lines changed

test/linkList.test.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { findLinkEnd, findLinkItemByIndex } from "../utils/linkList"
2+
import { LinkList, ListNode } from "../链表/myLinkList"
3+
4+
describe("链表测试", () => {
5+
const link = new LinkList()
6+
link.root.val = 1
7+
8+
link.add(new ListNode(2))
9+
link.add(new ListNode(3))
10+
link.add(new ListNode(4))
11+
test("添加链表元素", () => {
12+
expect(link.add(new ListNode(5))).toEqual({ val: 5, next: null })
13+
expect( () => link.add( 111 )).toThrow('传入元素不匹配')
14+
expect( () => link.add( { val: 5, next: null} )).toThrow('传入元素不匹配')
15+
expect( () => link.add( [] )).toThrow('传入元素不匹配')
16+
})
17+
test("查找链表索引元素", () => {
18+
expect( findLinkItemByIndex(link.root,0) ).toEqual( link.root )
19+
})
20+
test("指定索引删除链表元素", () => {
21+
expect( findLinkItemByIndex(link.root,1) ).toEqual( link.root.next )
22+
const cur = link.root.next.next
23+
link.remove(1)
24+
expect( findLinkItemByIndex(link.root,1) ).toEqual( cur )
25+
})
26+
27+
test("查找链表最后一个元素", () => {
28+
expect( findLinkEnd(link.root ) ).toEqual( {val: 5, next: null})
29+
})
30+
31+
})

链表/myLinkList.js

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
import { bianli, findLinkEnd, findLinkItemByIndex } from "../utils/linkList.js"
22

3-
class ListNode {
3+
export class ListNode {
44
val = null
55
next = null
66
constructor(val = null) {
77
this.val = val
88
}
99
}
1010

11-
class LinkList {
11+
export class LinkList {
1212
root = null
1313
constructor(root) {
1414
if (root instanceof ListNode) {
@@ -35,18 +35,6 @@ class LinkList {
3535
const newNext = curr.next.next;
3636
curr.next = newNext
3737
}
38-
3938
}
4039

41-
const link = new LinkList()
42-
link.root.val = 1
43-
link.add(new ListNode(2))
44-
link.add(new ListNode(3))
45-
link.add(new ListNode(4))
46-
47-
link.remove(2)
48-
// console.log(link)
4940

50-
// bianli(link.root)
51-
// console.log( findLinkEnd(link.root))
52-
// console.log( findLinkItemByIndex(link.root, 4) )

0 commit comments

Comments
 (0)