[자료구조][자바스크립트] 연결리스트(linked list)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const linkedListNode = class LinkedListNode {
    constructor(value, next = null) {
        this.value = value;
        this.next = next;
    }
}

const linkedList = class LinkedList {
    constructor() {
        this.head = null;
        this.length = 0;
    }

    append(value) {
        const node = new linkedListNode(value);
        let current = this.head;
        if (!current) { // 리스트가 비어있음
            this.head = node;
            this.length++;
            return node;
        } else {
            while (current.next) { //리스트의 끝을 찾아서
                current = current.next;
            }
            current.next = node; //끝에 추가
            this.length++;
            return node;
        }
    }

    find(position) {
        let current = this.head;
        let count = 0;
        while (count < position) {
            current = current.next;
            count++;
        }
        return current? current.value : null;
    }

    delete(position) {
        let current = this.head;
        let before;
        let remove;
        let count = 0;
        if (position == 0) { //제일 앞 삭제
            remove = this.head;
            this.head = this.head.next;
            this.length--;
            return remove;
        } else {
            console
            while (count < position) {
                before = current;
                count++;
                current = current.next;
            }
            remove = current;
            before.next = remove? remove.next : null;
            this.length--;
            return remove;
        }
    }
}

let testLink = new linkedList();
console.log(testLink);
testLink.append(3);
console.log(testLink)
testLink.append(4);
console.log(testLink)
console.log(testLink.delete(1))
console.log(testLink)
1
2
3
4
5
6
7
8
LinkedList { head: null, length: 0 }
LinkedList { head: LinkedListNode { value: 3, next: null }, length: 1 }
LinkedList {
  head:
   LinkedListNode { value: 3, next: LinkedListNode { value: 4, next: null } },
  length: 2 }
LinkedListNode { value: 4, next: null }
LinkedList { head: LinkedListNode { value: 3, next: null }, length: 1 }

Built with Hugo
Theme Stack designed by Jimmy