2022-12-16 15:49:09 +08:00
|
|
|
|
// File: ListNode.cs
|
|
|
|
|
// Created Time: 2022-12-16
|
|
|
|
|
// Author: mingXta (1195669834@qq.com)
|
|
|
|
|
|
2023-04-24 04:20:51 +08:00
|
|
|
|
namespace hello_algo.utils;
|
2023-02-08 22:18:02 +08:00
|
|
|
|
|
2023-04-23 03:03:12 +08:00
|
|
|
|
/* Definition for a singly-linked list node */
|
|
|
|
|
public class ListNode {
|
2023-02-08 22:18:02 +08:00
|
|
|
|
public int val;
|
|
|
|
|
public ListNode? next;
|
|
|
|
|
|
2023-04-23 03:03:12 +08:00
|
|
|
|
public ListNode(int x) {
|
2023-02-08 22:18:02 +08:00
|
|
|
|
val = x;
|
|
|
|
|
}
|
2022-12-16 15:49:09 +08:00
|
|
|
|
|
2023-04-23 03:03:12 +08:00
|
|
|
|
/* Generate a linked list with an array */
|
|
|
|
|
public static ListNode? ArrToLinkedList(int[] arr) {
|
2023-10-08 01:33:46 +08:00
|
|
|
|
ListNode dum = new(0);
|
2023-02-08 22:18:02 +08:00
|
|
|
|
ListNode head = dum;
|
2023-04-23 03:03:12 +08:00
|
|
|
|
foreach (int val in arr) {
|
2023-02-08 22:18:02 +08:00
|
|
|
|
head.next = new ListNode(val);
|
|
|
|
|
head = head.next;
|
2022-12-16 15:49:09 +08:00
|
|
|
|
}
|
2023-02-08 22:18:02 +08:00
|
|
|
|
return dum.next;
|
|
|
|
|
}
|
2022-12-16 15:49:09 +08:00
|
|
|
|
|
2023-04-23 03:03:12 +08:00
|
|
|
|
/* Get a list node with specific value from a linked list */
|
|
|
|
|
public static ListNode? GetListNode(ListNode? head, int val) {
|
|
|
|
|
while (head != null && head.val != val) {
|
2023-02-08 22:18:02 +08:00
|
|
|
|
head = head.next;
|
2022-12-16 15:49:09 +08:00
|
|
|
|
}
|
2023-02-08 22:18:02 +08:00
|
|
|
|
return head;
|
|
|
|
|
}
|
2022-12-16 15:49:09 +08:00
|
|
|
|
|
2023-04-23 03:03:12 +08:00
|
|
|
|
public override string? ToString() {
|
2023-02-08 22:18:02 +08:00
|
|
|
|
List<string> list = new();
|
|
|
|
|
var head = this;
|
2023-04-23 03:03:12 +08:00
|
|
|
|
while (head != null) {
|
2023-02-08 22:18:02 +08:00
|
|
|
|
list.Add(head.val.ToString());
|
|
|
|
|
head = head.next;
|
2022-12-16 15:49:09 +08:00
|
|
|
|
}
|
2023-02-08 22:18:02 +08:00
|
|
|
|
return string.Join("->", list);
|
2022-12-16 15:49:09 +08:00
|
|
|
|
}
|
2023-02-08 22:18:02 +08:00
|
|
|
|
}
|