从链表中删除元素
//删除链表中第index(o-based)个位置的元素,返回删除的全速 //在链表中不是一个常用的操作,练习用:) public E remove(int index) { if (index < 0 || index > size) throw new IllegalArgumentException("Set failed.Illegal index."); Node prev = dummyHead; for(int i = 0; i < index ; i ++){ prev = prev.next; } Node retNode = prev.next; prev.next = retNode.next; retNode.next = null; size --; return retNode.e; } //删除链表的第一个元素 public E removeFirst(){ return remove(0); } //删除元素的最后一个元素 public E removeLast(){ return remove(size - 1); }
public class Main { public static void main(String[] args) { LinkedList<Integer> linkedList = new LinkedList<>(); for(int i = 0 ; i < 5; i ++){ linkedList.addFirst(i); System.out.println(linkedList); } linkedList.add(2,666); System.out.println(linkedList); linkedList.remove(2); System.out.println(linkedList); linkedList.removeFirst(); System.out.println(linkedList); linkedList.removeLast(); System.out.println(linkedList); } }
0->null 1->0->null 2->1->0->null 3->2->1->0->null 4->3->2->1->0->null 4->3->666->2->1->0->null 4->3->2->1->0->null 3->2->1->0->null 3->2->1->null