链表的定义
class LN{ int data; public LN next; public LN(int data) { this.data = data; this.next = null; } }
链表的新增、按索引删除、按key值删除
public class ListPractice { static LN head = null; public static int length; public static void main(String[] args) { int[] nums = {1,2,3,4}; for (int i = 0; i < nums.length; i++) { insertLN(nums[i]); } deleteLN(1); deleteLNIndex(2); LN q = head; while(q!=null){ System.out.println(q.data); q = q.next; } } //插入 public static void insertLN(int num){ LN p = new LN(num); if(head == null){ head = p; length++; return; } LN q = head; while(q.next!=null){ q = q.next; } q.next = p; length++; } //按key值删除 public static void deleteLN(int num){ if(head != null){ LN p = head; LN q = p.next; if(p.data == num){ head = q; } while(q!=null){ if(q.data==num){ p.next = q.next; return; } p = q; q = q.next; } } } //按索引删除 public static void deleteLNIndex(int index){ LN p = head; LN q = p.next; if(index<1||index>length){ return; } if(index == 1){ head = head.next; return; } for (int i = 2; i < index; i++) { p = q; q = q.next; } p.next = q.next; }}