-
Notifications
You must be signed in to change notification settings - Fork 824
/
ListNode.java
39 lines (32 loc) · 971 Bytes
/
ListNode.java
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
//Definition for singly-linked list.
public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) {
val = x;
}
// 链表节点的构造函数
// 使用arr为参数,创建一个链表,当前的ListNode为链表头结点
public ListNode(int[] arr){
if(arr == null || arr.length == 0)
throw new IllegalArgumentException("arr can not be empty");
this.val = arr[0];
ListNode cur = this;
for(int i = 1 ; i < arr.length ; i ++){
cur.next = new ListNode(arr[i]);
cur = cur.next;
}
}
// 以当前节点为头结点的链表信息字符串
@Override
public String toString(){
StringBuilder s = new StringBuilder();
ListNode cur = this;
while(cur != null){
s.append(cur.val + "->");
cur = cur.next;
}
s.append("NULL");
return s.toString();
}
}