我们都知道邻接链表内部结构其实就是数组+链表构成的。 大致如下图: 在知道数组的遍历和链表的遍历之后,邻接链表的遍历自然也会了。 构建邻接链表结构并遍历
public class Node {
public int val;
public Node next;
public Node ( int val) {
this . val = val;
}
}
public class Main2 {
public static void main ( String[ ] args) {
Node[ ] nodes = new Node [ 3 ] ;
Node a1 = new Node ( 1 ) ;
Node a2 = new Node ( 2 ) ;
Node a3 = new Node ( 3 ) ;
a1. next = a2;
a2. next = a3;
Node b1 = new Node ( 4 ) ;
Node b2 = new Node ( 5 ) ;
Node b3 = new Node ( 6 ) ;
b1. next = b2;
b2. next = b3;
Node c1 = new Node ( 7 ) ;
Node c2 = new Node ( 8 ) ;
Node c3 = new Node ( 9 ) ;
c1. next = c2;
c2. next = c3;
nodes[ 0 ] = a1;
nodes[ 1 ] = b1;
nodes[ 2 ] = c1;
for ( int i = 0 ; i < nodes. length; i++ ) {
Node head = nodes[ i] ;
while ( head != null) {
System. out. println ( head. val) ;
head = head. next;
}
}
}
}