Skip to content

Commit db53cec

Browse files
authored
数组转化为链表
this调用本类中的其他构造方法,由于没有传值,就是将一个类传递给另一个。
1 parent ee2db08 commit db53cec

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

ListNode

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class ListNode {
2+
public int val;
3+
public ListNode next;
4+
5+
public ListNode(int x) {
6+
val=x;
7+
}
8+
9+
public ListNode(int[] arr) {
10+
if(arr==null||arr.length==0) {
11+
throw new IllegalArgumentException("arr can not be empty");
12+
}
13+
this.val=arr[0];
14+
ListNode cur=this;
15+
for(int i=1;i<arr.length;i++) {
16+
cur.next=new ListNode(arr[i]);
17+
cur=cur.next;
18+
}
19+
}
20+
@Override
21+
public String toString() {
22+
StringBuilder res=new StringBuilder();
23+
ListNode cur=this;
24+
while(cur!=null) {
25+
res.append(cur.val+"->");
26+
cur=cur.next;
27+
}
28+
res.append("NULL");
29+
return res.toString();
30+
}
31+
public static void main(String[] args) {
32+
// TODO Auto-generated method stub
33+
int[] nums= {1,2,6,3,4,5,6};
34+
ListNode head=new ListNode(nums);
35+
System.out.println(head);
36+
}
37+
}

0 commit comments

Comments
 (0)