1.节点类ListNode
class ListNode<K>{
public next: ListNode<K> | null;
constructor(public element: K) {
this.next = null;
}
}
2.链表类LinkList
class LinkList<T>{
public count: number
public head: ListNode<T> | null
constructor() {
this.head = null
this.count = 0
}
/**
* 在链表尾部插入元素
* @param element
*/
push(element: T){
const node = new ListNode(element)
if (this.head == null) {
this.head = node
} else {
let current = this.head
while (current.next != null) {
current = current.next
}
current.next = node
}
this.count++
}
/**
* 通过位置索引查找元素
* @param index
*/
findByIndex(index: number):ListNode<T> | null {
if (index < this.count && index >= 0) {
if (this.head != null) {
let current = this.head
let tmp: number = 0
while (current.next != null&& tmp < index) {
current = current.next
tmp++
}
return current
}
}
return null
}
/**
* 移除指定位置的元素
* @param index
*/
removeByIndex(index: number) {
if (this.head != null) {
if (index === 0) {
this.head = this.head.next
} else {
let previous = this.findByIndex(index - 1)
let current = this.findByIndex(index)
if (previous&¤t) {
previous.next = current.next
}
}
this.count--
}
}
/**
* 查找元素位置,如果没有找到就返回-1
* @param element
*/
findElIndex(element: T): number{
let current = this.head
if (current == null) {
return -1
} else {
let index: number = 0
while (current.next != null) {
if (current.element === element) {
return index
}
current = current.next
index++
}
return -1
}
}
/**
* 在指定位置插入元素
* @param element
* @param index
*/
insert(element: T, index: number) {
let previous = this.findByIndex(index - 1)
let current = this.findByIndex(index)
let newNode = new ListNode(element)
if (previous && current) {
previous.next = newNode
previous.next.next = current
}
if (previous && !current) {
previous.next = newNode
}
if (current && !previous) {
this.head = newNode
this.head.next = current
}
this.count++
}
/**
* 将链表转换为字符串
*/
toString() {
let tmpString: string = ''
let current = this.head
if (current == null) {
return ''
} else {
while (current.next != null) {
tmpString = `${current.element}${tmpString}`
current = current.next
}
return tmpString
}
}
}