什么时候选择LinkedList?
来源:互联网 发布:unity3d怎么做建筑 编辑:程序博客网 时间:2024/05/21 10:38
LinkedList即单链表,如下图
LinkedList优点:
- 长度可变
- 插入删除简单
LinkedList缺点:
- 不能随机访问,必须从head结点顺序访问,所以也就不能够二分查找
- 存储pointer消耗内存
下面是LinkedList的简单实现以及简单操作(各个位置插入新节点,打印单链表):
class LinkedList{ Node head; class Node { int data; Node next; Node(int d) {data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { Node new_node = new Node(new_data); new_node.next = head; head = new_node; } /* Inserts a new node after the given prev_node. */ public void insertAfter(Node prev_node, int new_data) { if (prev_node == null) { System.out.println("The given previous node cannot be null"); return; } Node new_node = new Node(new_data); new_node.next = prev_node.next; prev_node.next = new_node; } /* Appends a new node at the end. This method is defined inside LinkedList class shown above */ public void append(int new_data) { Node new_node = new Node(new_data); if (head == null) { head = new Node(new_data); return; } new_node.next = null; Node last = head; while (last.next != null) last = last.next; last.next = new_node; return; } /* This function prints contents of linked list starting from the given node */ public void printList() { Node tnode = head; while (tnode != null) { System.out.print(tnode.data+" "); tnode = tnode.next; } } public static void main(String[] args) { /* Start with the empty list */ LinkedList llist = new LinkedList(); // Insert 6. So linked list becomes 6->NUllist llist.append(6); // Insert 7 at the beginning. So linked list becomes // 7->6->NUllist llist.push(7); // Insert 1 at the beginning. So linked list becomes // 1->7->6->NUllist llist.push(1); // Insert 4 at the end. So linked list becomes // 1->7->6->4->NUllist llist.append(4); // Insert 8, after 7. So linked list becomes // 1->7->8->6->4->NUllist llist.insertAfter(llist.head.next, 8); System.out.println("\nCreated Linked list is: "); llist.printList(); }}
供后续方便查阅
0 0
- 什么时候选择LinkedList?
- 什么时候用ArrayList,什么时候用LinkedList
- 什么时候用Arraylist和linkedList
- 什么时候选择TCP,什么时候选择UDP?
- 什么时候选择TCP,什么时候选择UDP?
- 在项目什么时候选择使用GCD,什么时候选择NSOperation?
- 在项目什么时候选择使用GCD,什么时候选择NSOperation
- 在项目什么时候选择使用GCD,什么时候选择NSOperation?
- Item 27: 明白什么时候选择重载,什么时候选择universal引用
- 什么时候选择显式链接
- ArraryList 和 LinkedList 如何选择?
- 什么时候选择用IDA而不是BFS
- 什么时候
- 什么时候
- 什么时候使用接口?什么时候使用抽象?选择Java接口还是抽象类 (转)
- 什么时候使用接口?什么时候使用抽象?选择Java接口还是抽象类 (转)
- 什么时候使用接口?什么时候使用抽象?选择Java接口还是抽象类 (转)
- 什么时候使用接口?什么时候使用抽象?选择Java接口还是抽象类
- 多线程下载
- 纯Java的高性能长连接RPC解决方案
- PAT 1023
- js如何准确获取当前页面url网址信息
- JAVA中泛型和集成体系
- 什么时候选择LinkedList?
- 【面试题】剑指offer 16
- C++面试问题——整理篇
- QT5——SpinBox、Double SpinBox 和Slider
- 1003. Emergency (25) 最短路问题
- Hive编程指南05---Hive查询
- JAVA利用第三方平台发送短信验证码。
- Bootloader
- QT生成DLL,调用DLL