java LinkedList的實(shí)例詳解
站在Java的角度看,玩隊(duì)列不就是玩對(duì)象引用對(duì)象嘛!
實(shí)例代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
public class LinkedList<E> implements List<E>, Deque<E> { Node<E> first; Node<E> last; int size; public boolean add(E e) { final Node<E> l = last; final Node<E> newNode = new Node<>(l, e, null ); last = newNode; if (l == null ) first = newNode; else l.next = newNode; size++; modCount++; return true ; } private static class Node<E> { E item; Node<E> next; Node<E> prev; Node(Node<E> prev, E element, Node<E> next) { this .item = element; this .next = next; this .prev = prev; } } } |
單鏈表反轉(zhuǎn):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
/** * 遞歸,在反轉(zhuǎn)當(dāng)前節(jié)點(diǎn)之前先反轉(zhuǎn)后續(xù)節(jié)點(diǎn) */ public static Node reverse(Node head) { if ( null == head || null == head.getNextNode()) { return head; } Node reversedHead = reverse(head.getNextNode()); head.getNextNode().setNextNode(head); head.setNextNode( null ); return reversedHead; } /** * 遍歷,將當(dāng)前節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)緩存后更改當(dāng)前節(jié)點(diǎn)指針 * */ public static Node reverse2(Node head) { if ( null == head) { return head; } Node pre = head; Node cur = head.getNextNode(); Node next; while ( null != cur) { next = cur.getNextNode(); cur.setNextNode(pre); pre = cur; cur = next; } //將原鏈表的頭節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)置為null,再將反轉(zhuǎn)后的頭節(jié)點(diǎn)賦給head head.setNextNode( null ); head = pre; return head; } |
對(duì)于數(shù)組問題,一般我們要新建數(shù)組,必要時(shí)移動(dòng)下標(biāo)
以上就是java LinkedList 的實(shí)例,如有疑問請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
原文鏈接:http://wely.iteye.com/blog/2326330