11package cn .byhieg .collectiontutorial .listtutorial ;
22
3+ import apple .laf .JRSUIFocus ;
4+
35/**
46 * Created by byhieg on 17/2/15.
57 * Mail to byhieg@gmail.com
@@ -13,6 +15,69 @@ public class SimpleLinkedList<E> {
1315 private Node <E > last ;
1416
1517
18+
19+ public boolean add (E element ) {
20+ addAtLast (element );
21+ return true ;
22+ }
23+
24+ private void addAtLast (E element ){
25+ Node <E > l = last ;
26+ Node <E > node = new Node <E >(element ,null ,l );
27+ last = node ;
28+ if (l == null ) {
29+ first = node ;
30+ }else {
31+ l .next = node ;
32+ }
33+ size ++;
34+ }
35+
36+ public void add (int index , E element ) {
37+ checkRangeForAdd (index );
38+ if (index == size ){
39+ addAtLast (element );
40+ }else {
41+ Node <E > l = node (index );
42+ addBeforeNode (element ,l );
43+ }
44+ }
45+
46+ private void addBeforeNode (E element ,Node <E > specifiedNode ){
47+ Node <E > preNode = specifiedNode .prev ;
48+ Node <E > newNode = new Node <>(element , specifiedNode ,preNode );
49+ if (preNode == null ) {
50+ first .next = newNode ;
51+ }else {
52+ preNode .next = newNode ;
53+ }
54+ specifiedNode .prev = newNode ;
55+ size ++;
56+ }
57+
58+
59+ private Node <E > node (int index ){
60+ if (index < (size <<1 )){
61+ Node <E > cursor = first ;
62+ for (int i = 0 ; i < index ; i ++) {
63+ cursor = cursor .next ;
64+ }
65+ return cursor ;
66+ }else {
67+ Node <E > cursor = last ;
68+ for (int i = size -1 ; i > index ; i --) {
69+ cursor = cursor .prev ;
70+ }
71+ return cursor ;
72+ }
73+ }
74+
75+ private void checkRangeForAdd (int index ){
76+ if (index > size || index < 0 ) {
77+ throw new IndexOutOfBoundsException ("指定的index超过界限" );
78+ }
79+ }
80+
1681 private static class Node <E >{
1782 E item ;
1883 Node <E > next ;
0 commit comments