java LinkedList的实例详解
站在Java的角度看,玩队列不就是玩对象引用对象嘛!
实例代码:
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;
}
}
}
|
单链表反转:
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
|
/**
* 递归,在反转当前节点之前先反转后续节点
*/
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;
}
/**
* 遍历,将当前节点的下一个节点缓存后更改当前节点指针
*
*/
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;
}
//将原链表的头节点的下一个节点置为null,再将反转后的头节点赋给head
head.setNextNode( null );
head = pre;
return head;
}
|
对于数组问题,一般我们要新建数组,必要时移动下标
以上就是java LinkedList 的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://wely.iteye.com/blog/2326330