forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ListNode.java
52 lines (43 loc) · 1.36 KB
/
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
40
41
42
43
44
45
46
47
48
49
50
51
52
// Definition for singly-linked list.
// 在Java版本中,我们将LinkedList相关的测试辅助函数写在ListNode里
public class ListNode {
public int val;
public ListNode next = null;
public ListNode(int x) {
val = x;
}
// 根据n个元素的数组arr创建一个链表
// 使用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 curNode = this;
for(int i = 1 ; i < arr.length ; i ++){
curNode.next = new ListNode(arr[i]);
curNode = curNode.next;
}
}
ListNode findNode(int x){
ListNode curNode = this;
while(curNode != null){
if(curNode.val == x)
return curNode;
curNode = curNode.next;
}
return null;
}
// 返回以当前ListNode为头结点的链表信息字符串
@Override
public String toString(){
StringBuilder s = new StringBuilder("");
ListNode curNode = this;
while(curNode != null){
s.append(Integer.toString(curNode.val));
s.append(" -> ");
curNode = curNode.next;
}
s.append("NULL");
return s.toString();
}
}