package com.company;
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
int[] input = new int[]{1, 2, 3, 4, 5};
ListNode head = buildListNode(input);
while (head != null) {
System.out.println("val: " + head.val + "\tlistNode: " + head.next);
head = head.next;
}
}
/**
* 构造ListNode
*/
private static ListNode buildListNode(int[] input) {
ListNode first = null, last = null, newNode;
if (input.length > 0) {
for (int i = 0; i < input.length; i++) {
newNode = new ListNode(input[i]);
newNode.next = null;
if (first == null) {
first = newNode;
last = newNode;
} else {
last.next = newNode;
last = newNode;
}
}
}
return first;
}
}
打印结果
val: 1 listNode: com.company.ListNode@140e19d
val: 2 listNode: com.company.ListNode@17327b6
val: 3 listNode: com.company.ListNode@14ae5a5
val: 4 listNode: com.company.ListNode@131245a
val: 5 listNode: null
网友评论