Skip to content

Instantly share code, notes, and snippets.

@smallyunet
Last active November 4, 2019 03:28
Show Gist options
  • Save smallyunet/e430182ece420cc7ee844baf5948add6 to your computer and use it in GitHub Desktop.
Save smallyunet/e430182ece420cc7ee844baf5948add6 to your computer and use it in GitHub Desktop.
Building a singly linked list
/**
* @description Unidirectional linked data structure
* @author smallyu
* @date 2019/10/23 13:22
*/
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
/**
* @description Init ListNode with integer array
* @param arr new int[]{1, 2, 3}
*/
public ListNode(int[] arr) {
// It will get some trouble if input empty array []
// Because int field would init value to 0
if (arr == null || arr.length < 1) {
return;
}
this.val = arr[0];
ListNode node = this;
for (int i = 0; i < arr.length - 1; i++) {
node.next = new ListNode(arr[i + 1]);
node = node.next;
}
}
/**
* @description Print ListNode like array
* @return String ArrayList.toString()
*/
@Override
public String toString() {
List<Integer> list = new ArrayList<Integer> ();
ListNode node = this;
while (node != null) {
list.add(node.val);
node = node.next;
}
return list.toString();
}
}
// ListNode listNode = new ListNode(new int[]{1, 2, 3});
// System.out.println(listNode);
// [1, 2, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment