mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-26 22:56:28 +08:00
42 lines
875 B
Java
42 lines
875 B
Java
|
package include;
|
||
|
|
||
|
/**
|
||
|
* Definition for a singly-linked list node
|
||
|
*/
|
||
|
public class ListNode {
|
||
|
public int val;
|
||
|
public ListNode next;
|
||
|
|
||
|
public ListNode(int x) {
|
||
|
val = x;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Generate a linked list with an array
|
||
|
* @param arr
|
||
|
* @return
|
||
|
*/
|
||
|
public static ListNode arrToLinkedList(int[] arr) {
|
||
|
ListNode dum = new ListNode(0);
|
||
|
ListNode head = dum;
|
||
|
for (int val : arr) {
|
||
|
head.next = new ListNode(val);
|
||
|
head = head.next;
|
||
|
}
|
||
|
return dum.next;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Get a list node with specific value from a linked list
|
||
|
* @param head
|
||
|
* @param val
|
||
|
* @return
|
||
|
*/
|
||
|
public static ListNode getListNode(ListNode head, int val) {
|
||
|
while (head != null && head.val != val) {
|
||
|
head = head.next;
|
||
|
}
|
||
|
return head;
|
||
|
}
|
||
|
}
|