手动构造LeetCode的输入——链表
pu Lv999

在面试的时候,链表类题目很常见,我们通常需要共享屏幕在IDE里面敲代码,而不像LeetCode已经提前定义好了链表的数据结构,可以直接使用。 因此我们要学会手动构造链表,避免在面试中会写核心逻辑但是基本数据结构却写不出来。

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
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).append("->");
cur = cur.next;
}
s.append("NULL");
return s.toString();
}

public static void main(String[] args) {
int[] arr = new int[] {1, 2, 3, 4, 5};
ListNode node = new ListNode(arr);
System.out.println(node);
}

}