JAvaは103-104に慣れるまで
19221 ワード
今回の内容:linkedlist()
今回は前回arraylist()を引き継ぎ、自分でlinkedlist()を実現(内容が少ない)
実行結果:
4bbbbbb
今回は前回arraylist()を引き継ぎ、自分でlinkedlist()を実現(内容が少ない)
1 package list;
2 /**
3 * linkedlist
4 * @author acer
5 *
6 */
7 public class mylinkedlist {
8 private Node first;
9 private Node last;
10 private int size;
11 public void add(Object obj)
12 {
13 Node n=new Node();
14 if(first==null)
15 {
16 n.setPrevious(null);
17 n.setObj(obj);
18 n.setNext(null);
19 first=n;
20 last=n;
21 }
22 else
23 {
24 n.setPrevious(last);
25 n.setObj(obj);
26 n.setNext(null);
27 last.setNext(n);
28 last=n;
29 }
30 size++;
31 }
32 public void add(int index,Object obj)
33 {
34 Node temp=null;
35 Node newNode=new Node();
36 newNode.setObj(obj);
37 if(first!=null)
38 {
39 temp=first;
40 for(int i=0;i<index;i++)
41 {
42 temp=temp.getNext();
43 }
44 }
45 newNode.setPrevious(temp.getPrevious());
46 temp.getPrevious().setNext(newNode);
47 newNode.setNext(temp);
48 temp.setPrevious(newNode);
49 size++;
50
51 }
52 public Object get(int index)
53 {
54 rangeCheck(index);
55 Node temp=null;
56 if(first!=null)
57 {
58 temp=first;
59 for(int i=0;i<index;i++)
60 {
61 temp=temp.getNext();
62 }
63 }
64 return temp.getObj();
65 }
66 public void removefirst()
67 {
68 Node temp=null;
69 temp=first;
70 temp=temp.getNext();
71 temp.setPrevious(null);
72 first.setNext(null);
73 first=temp;
74 }
75 public void remove(int index)
76 {
77 rangeCheck(index);
78 Node temp=null;
79 if(first!=null)
80 {
81 temp=first;
82 for(int i=0;i<index;i++)
83 {
84 temp=temp.getNext();
85 }
86 }
87 if(temp!=null)
88 {
89 Node pre=temp.getPrevious();
90 Node ne=temp.getNext();
91 pre.setNext(ne);
92 ne.setPrevious(pre);
93 size--;
94 }
95
96 }
97 public void rangeCheck(int index)
98 {
99 if(index<0||index>=size)
100 {
101 try {
102 throw new Exception();
103 } catch (Exception e) {
104 e.printStackTrace();
105 }
106 }
107 }
108 public int size()
109 {
110 return size;
111 }
112 public static void main(String[] args)
113 {
114 mylinkedlist list=new mylinkedlist();
115 list.add("aaa");
116 list.add("bbb");
117 list.add("ccc");
118 list.add("ddd");
119 System.out.println(list.size());
120 System.out.println(list.get(1));
121 list.removefirst();
122 System.out.println(list.get(0));
123 }
124 }
125
126
127 class Node
128 {
129 private Node previous;
130 private Object obj;
131 private Node next;
132 public Node()
133 {
134 }
135 public Node(Node previous, Object obj, Node next) {
136 super();
137 this.previous = previous;
138 this.obj = obj;
139 this.next = next;
140 }
141 public Node getPrevious() {
142 return previous;
143 }
144 public void setPrevious(Node previous) {
145 this.previous = previous;
146 }
147 public Object getObj() {
148 return obj;
149 }
150 public void setObj(Object obj) {
151 this.obj = obj;
152 }
153 public Node getNext() {
154 return next;
155 }
156 public void setNext(Node next) {
157 this.next = next;
158 }
159 }
実行結果:
4bbbbbb