关于链表的一些问题的整理
链表的类通常表示如下:
public class ListNode { public int val; public ListNode next; public ListNode(int val, ListNode next=null) { this.val = val; this.next = next; } }
(一)创建链表
根据给定的数组使用尾插法和头插法创建链表
public static ListNode createListNode(int[] array) { ListNode node = new ListNode(array[0]); for (int i = 1; i < array.Length; i++) { addNode(node, array[i]); } return node; } private static void addNode(ListNode node, int val) { if (node.next == null) node.next = new ListNode(val); else addNode(node.next, val); }
public static ListNode headInsertNode(int[] array) { ListNode node = new ListNode(array[0]); for (int i = 1; i < array.Length; i++) { node = subHeadInsert(node, array[i]); } return node; } private static ListNode subHeadInsert(ListNode node, int val) { ListNode newNode = new ListNode(val); newNode.next = node; return newNode; }