标签:idt 容量 虚拟 tostring 分享图片 last inf public 需要
1.什么是链表
优点:不需要处理固定容量的问题
缺点:丧失了随机访问的能力
2.数组和链表的对比
3.在链表头添加元素
4.在链表中间添加元素
5.链表中添加节点的代码实现
public class LinkedList<E> { private class Node{ public E e; public Node next; public Node(E e,Node next){ this.e = e; this.next = next; } public Node(E e){ this(e,null); } public Node(){ this(null,null); } @Override public String toString(){ return e.toString(); } } private Node head; int size; public LinkedList(){ head = null; size =0; } //获取链表中的元素个数 public int getSize(){ return size; } //返回链表是否为空 public boolean isEmpty(){ return size == 0; } //在链表头添加新的元素e public void addFirst(E e){ // Node node = new Node(e); // node.next = head; // head = node; head = new Node(e,head); size ++; } //在链表的index位置添加新元素e public void add(int index,E e){ if(index < 0 || index > size) throw new IllegalArgumentException("Add failed.Illegal index."); if(index == 0) addFirst(e); else{ Node prev = head; for(int i = 0;i < index -1;i ++) prev =prev.next; // Node node =new Node(e); // node.next = prev.next; // prev.next = node; prev.next =new Node(e,prev.next); size ++; } } //在链表末尾添加新的元素e public void addLast(E e){ add(size,e); } }
6.使用链表的虚拟头结点
public class LinkedList<E> { private class Node{ public E e; public Node next; public Node(E e,Node next){ this.e = e; this.next = next; } public Node(E e){ this(e,null); } public Node(){ this(null,null); } @Override public String toString(){ return e.toString(); } } private Node dummyHead; private int size; public LinkedList(){ dummyHead = new Node(null,null); size =0; } //获取链表中的元素个数 public int getSize(){ return size; } //返回链表是否为空 public boolean isEmpty(){ return size == 0; } //在链表的index位置添加新元素e public void add(int index,E e){ if(index < 0 || index > size) throw new IllegalArgumentException("Add failed.Illegal index."); Node prev = dummyHead; for(int i = 0;i < index;i ++) prev =prev.next; prev.next =new Node(e,prev.next); size ++; } //在链表头添加新的元素e public void addFirst(E e){ add(0,e); } //在链表末尾添加新的元素e public void addLast(E e){ add(size,e); } }
标签:idt 容量 虚拟 tostring 分享图片 last inf public 需要
原文地址:https://www.cnblogs.com/zouke1220/p/9496003.html