package 链表;
import java.util.ArrayList;
class Node{
int val;
Node next;
Node(int val){
this.val = val;
}
}
public class Main1 {
public static Node arrayToNode(int[] arr){
Node head = new Node(arr[0]); // 把数组的第一个位置定义为头结点
Node other = head; // 一个指针,此时指向头结点
for(int i=1;i
Node temp = new Node(arr[i]);
other.next = temp;
other = other.next;
}//在此处打印结点容易导致head的变化
return head;
}
public static void printNode(Node node){
while(node!=null){
System.out.print(node.val+" ");
node = node.next;
}
}
public static void nodeTolist(Node node){
ArrayList list = new ArrayList<>();
while(node != null){
list.add(node.val);
node = node.next;
}
System.out.println();
System.out.println(list);
}
public static void main(String[] args){
int[] arr = new int[]{1,2,3,4,5,6};
Node node = arrayToNode(arr);
printNode(node);
nodeTolist(node);
}
}
标签:Node,node,arr,Java,val,int,链表,互换,new
来源: https://blog.csdn.net/qq_38826019/article/details/101097823