自定义链表ListNode类
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
将链表转换成数组
//将链表转换成数组
public class Test1 {
public static void main(String[] args) {
Test1 test1 = new Test1();
int[] a = {1, 9, 9, 9, 9, 9, 9, 9, 9, 9};
ListNode l1 = test1.arrayToListNode(a);
test1.printListNode(l1);
}
//数组转换成链表
public ListNode arrayToListNode(int[] s) {
ListNode root = new ListNode(s[0]);//生成链表的根节点,并将数组的第一个元素的值赋给链表的根节点
ListNode other = root;//生成另一个节点,并让other指向root节点,other在此作为一个临时变量,相当于指针
for (int i = 1; i < s.length; i++) {//由于已给root赋值,所以i从1开始
ListNode temp = new ListNode(s[i]);//每循环一次生成一个新的节点,并给当前节点赋值
other.next = temp;//将other的下一个节点指向生成的新的节点
other = temp;//将other指向最后一个节点(other的下一个节点) other=other.getNext();
}
return root;
}
/**
* 遍历一个链表
*/
public void printListNode(ListNode l) {
while (l != null) {
System.out.print(l.val + " ");
l = l.next;
}
}
}
将数组转换成链表
//将链表转换成数组
public class Test2 {
public static void main(String[] args) {
Test2 test2 = new Test2();
ListNode l1 = new ListNode(0);
l1.next = new ListNode(1);
l1.next.next = new ListNode(2);
l1.next.next.next = new ListNode(3);
l1.next.next.next.next = new ListNode(4);
test2.printArrays(test2.listNodeToArray(l1));
}
//输出数组
public void printArrays(int[] ints) {
for (int x : ints) {
System.out.print(x + " ");
}
}
//将链表转换成数组
public int[] listNodeToArray(ListNode l) {
int size = listNodeSize(l);
int[] ints = new int[size];
int index = 0;
while (l != null) {
ints[index] = l.val;
l = l.next;
index++;
}
return ints;
}
//求链表的长度
public int listNodeSize(ListNode l) {
int size = 0;
while (l != null) {
size++;
l = l.next;
}
return size;
}
//遍历一个链表
public void printListNode(ListNode l) {
while (l != null) {
System.out.print(l.val + " ");
l = l.next;
}
}
}