前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Thinking--从尾到头打印链表

Thinking--从尾到头打印链表

作者头像
奋飛
发布2020-05-28 17:02:29
3280
发布2020-05-28 17:02:29
举报
文章被收录于专栏:Super 前端Super 前端

Thinking系列,旨在利用10分钟的时间传达一种可落地的编程思想。

使用 typescript 生成链表

代码语言:javascript
复制
interface node<T> {
    next: node<T> | null
    element: T
}

class LinkedNode<T> implements node<T> {
    element: T
    next: node<T> | null = null
    constructor(element: T, next: node<T> | null = null) {
        this.element = element
        this.next = next
    }
}

class LinkedList<T> {
    length: number = 0
    head: node<T> | null = null
    append(element: node<T>) {
        let node: node<T> = element
        if (this.head === null) {
            this.head = node
        } else {
          	// 不改变head指针
            let current = this.head
            while (current.next) {
                current = current.next
            }
            current.next = node
        }
        this.length++
    }
}

需求: 如,链表信息{"length":3,"head":{"next":{"next":{"next":null,"element":"c"},"element":"b"},"element":"a"}},链表倒序输出c b a

代码语言:javascript
复制
var testLinkedList = new LinkedList<string>()
testLinkedList.append(new LinkedNode<string>('a'))
testLinkedList.append(new LinkedNode<string>('b'))
testLinkedList.append(new LinkedNode<string>('c'))

常规思路

循环保存,然后倒序输出

代码语言:javascript
复制
function printLinkedListReversing (head: node<string>): void {
    let result: string[] = []
    while(head !== null) {
        result.push(head.element)
        head = head.next
    }
    console.log(result.reverse())
}    

延伸

倒叙输出(先进后出 FILO),典型的栈。 依靠递归(递归本质上是一个栈结构)

代码语言:javascript
复制
function printLinkedListReversing_recursion(head: node<string>): void{
    if (head !== null) {
        if (head.next != null) {
            printLinkedListReversing_recursion(head.next)
        }
        console.log(head.element)
    }
}

需要注意的是,当链表过长时,会导致函数调用的层级过深,可能导致调用栈溢出。

扩展: 数组存储中间状态

代码语言:javascript
复制
function printLinkedListReversing(head: node<string>, result: Array<string> = []): Array<string> {
    if (head !== null) {
        if (head.next != null) {
            printLinkedListReversing(head.next, result)
        }
      	console.log(head.element)
        result.push(head.element)
    }
    return result
}

console.log(printLinkedListReversing(testLinkedList.head, []))	// [ 'c', 'b', 'a' ]

物理结构:

  • 顺序存储结构:数组
  • 链式存储结构:链表

逻辑结构:

  • 线性结构:顺序表、栈、队列
  • 非线性结构:树、图
在这里插入图片描述
在这里插入图片描述

数组:读操作多、写操作少的场景。 非常高效的随机访问能力;插入和删除元素效率不高。 链表:灵活地进行插入和删除操作。

查找

更新

插入

删除

数组

O(1)

O(1)

O(n)

O(n)

链表

O(n)

O(1)

O(1)

O(1)

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-11-20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 常规思路
  • 延伸
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档