1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
public class ListNode { private static ListNode head = new ListNode();
private int val; private ListNode next; public ListNode() { } public ListNode(int val) { this.val = val; } public ListNode(int val, ListNode next) { this.val = val; this.next = next; }
public int size(){ int len = 0; ListNode temp = head; while(temp!=null){ temp = temp.next; len++; }
return len; }
public void print(){ ListNode temp = head.next; while(temp!=null){ System.out.print(temp.val+"->"); temp = temp.next; } System.out.println("null"); }
public void add(int val){ ListNode newNode = new ListNode(val); ListNode temp = head; while(temp.next!=null){ temp = temp.next; } temp.next = newNode; }
public void add(int index,int val){ if(index>size() && index <=0){ System.out.println("不合法"); return; } ListNode newNode = new ListNode(val); ListNode temp = head;
for (int i = 1; i < index; i++) { temp = temp.next; } ListNode nextNode = temp.next; temp.next = newNode; newNode.next = nextNode; }
public void del(int index){ if(index>size() && index <=0){ System.out.println("不合法"); return; } ListNode cur = head; ListNode prev = null; for (int i = 0; i < index; i++) { prev = cur; cur = cur.next; } if(prev==null) head.next = cur.next; else { prev.next = cur.next; }
} public void contain(int val){ ListNode temp = head; while (temp!=null){ if(temp.val == val) { System.out.println("包含"+val); return; } temp = temp.next; } System.out.println("不包含"+val); }
}
|