Helpers
Shared ListNode for linked-list problems.
- File
- ListNode.java
- Path
- pkg5leetcode/common/ListNode.java
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1/**2 * Shared ListNode for linked-list problems.3 *4 * Learn once, reuse across Blind75 / Interview 150 / Top 100.5 *6 * Compile with a problem file:7 * javac pkg5leetcode/common/ListNode.java pkg5leetcode/blind75/YourProblem.java8 * java -cp pkg5leetcode/common;pkg5leetcode/blind75 YourProblem9 *10 * Or study this shape and keep a nested copy for single-file `java YourProblem.java` runs.11 */12public class ListNode {13 public int val;14 public ListNode next;15 16 public ListNode() {}17 18 public ListNode(int val) {19 this.val = val;20 }21 22 public ListNode(int val, ListNode next) {23 this.val = val;24 this.next = next;25 }26 27 /** Build a list from values, e.g. of(1, 2, 3). */28 public static ListNode of(int... values) {29 ListNode dummy = new ListNode(0);30 ListNode cur = dummy;31 for (int v : values) {32 cur.next = new ListNode(v);33 cur = cur.next;34 }35 return dummy.next;36 }37 38 @Override39 public String toString() {40 StringBuilder sb = new StringBuilder();41 ListNode cur = this;42 while (cur != null) {43 if (sb.length() > 0) sb.append(" -> ");44 sb.append(cur.val);45 cur = cur.next;46 }47 return sb.toString();48 }49}