ListNode
public class ListNode {
public int val;
public ListNode next;
public ListNode() {}
public ListNode(int val) { this.val = val; }
public ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
尾插法构建带头节点的单链表
public ListNode creatListByArray(ListNode head, int[] nums) {
ListNode p = head;
for (int i = 0; i < nums.length; i++) {
ListNode q = new ListNode();
p.next = q;
p.next.val = nums[i];
p = p.next;
}
return head;
}
使链表变成环路
public ListNode createCycleList(ListNode head, int pos) {
ListNode p = head;
ListNode q = new ListNode();
if (pos == 0 && p.next == null) {
p.next = head;
} else {
int index = 0;
while (p.next != null) {
if (index == pos) {
q = p;
}
p = p.next;
index++;
}
if (pos <= index) {
p.next = q;
}
}
return head;
}
使两个链表相交
public void createIntersectionList(ListNode headA, ListNode headB, int skipA, int skipB) {
ListNode p = headA;
ListNode q = headB;
while (p != null && skipA > 1) {
p = p.next;
skipA--;
}
while (q != null && skipB > 1) {
q = q.next;
skipB--;
}
q.next = p.next;
}
根据val查询结点
public ListNode findNodeByVal(ListNode head, int val) {
ListNode p = head;
while (p != null) {
if (p.val == val) {
return p;
}
p = p.next;
}
return null;
}
打印带头结点的链表
public void showList(ListNode head) {
if (head == null) {
System.out.println();
return;
}
ListNode p = head.next;
while (p != null) {
System.out.print(p.val + " ");
p = p.next;
}
System.out.println();
}
打印不带头结点的链表
public void showNoHeadList(ListNode head) {
if (head == null) {
System.out.println();
return;
}
ListNode p = head;
while (p != null) {
System.out.print(p.val + " ");
p = p.next;
}
System.out.println();
}
打印结点
public void showNode(ListNode node) {
if (node == null) {
System.out.println();
} else {
System.out.println(node.val);
}
}