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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116 |
<span style= "font-size: 16px;" ><strong>PS:双向链表(每个节点含有指向前一个节点的前驱与后一个节点的后继)</strong></span> public class DoublyLinkedList { static
class Node { private
Object data; private
Node prev; public
Node getPrev() { return
prev; } public
void setPrev(Node prev) { this .prev = prev; } private
Node next; public
Node(Object value) { this .data = value; } public
Object getData() { return
data; } public
void setData(Object data) { this .data = data; } public
Node getNext() { return
next; } public
void setNext(Node next) { this .next = next; } @Override public
String toString() { return
String.valueOf(data); } } private
Node head; // 头节点 public
DoublyLinkedList() { head = new
Node( null ); } // 双向链表表头插入节点 public
void addFirst(Object value) { Node node = new
Node(value); if
(head.next == null ) { head.next = node; node.prev = head; } else
{ node.prev = head; node.next = head.next; head.next.prev = node; head.next = node; } // head=node; } // 删除表头 public
void removeFirst() { Node node = head.next; if
(node.next != null ) { node.next.prev = head; head.next = node.next; } } // 顺序打印链表 public
void printList() { Node node = head.next; while
(node != null ) { System.out.print(node.data + " " ); node = node.next; } System.out.println(); } // 逆序打印链表 public
void reversePrintList() { Node node = head.next; Node tail = null ; while
(node.next != null ) { node = node.next; } tail = node; // System.out.println(tail.data); while
(tail.prev != null ) { System.out.print(tail.data + " " ); tail = tail.prev; } System.out.println(); } public
static void main(String[] args) { DoublyLinkedList linkedList = new
DoublyLinkedList(); for
( int i = 0 ; i < 10 ; i++) { linkedList.addFirst(i); } System.out.println( "顺序打印链表" ); linkedList.printList(); System.out.println( "逆序打印链表" ); linkedList.reversePrintList(); System.out.println( "依次删除头结点" ); for
( int i = 0 ; i < 10 ; i++) { linkedList.removeFirst(); linkedList.printList(); } } } |
原文:http://www.cnblogs.com/cugb-2013/p/3675442.html