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
| class Node { int val; Node next; Node(){} Node(int val){ this.val = val; } } class MyLinkedList { int size; Node head;
public MyLinkedList() { size = 0; head = new Node(0);
} public int get(int index) { if(index < 0 || index >= size) return -1;
Node cur = head; for(int i=0;i<=index;i++){ cur = cur.next; }
return cur.val; } public void addAtHead(int val) { addAtIndex(0,val); } public void addAtTail(int val) { addAtIndex(size,val); } public void addAtIndex(int index, int val) { if(index >size) return; if(index < 0) index = 0; size++; Node cur = head; for(int i = 0 ;i<index;i++) cur = cur.next;
Node node = new Node(val); node.next = cur.next; cur.next = node; } public void deleteAtIndex(int index) { if(index<0 || index >= size) return; Node cur = head; size--; for(int i = 0; i<index ;i++) cur = cur.next; cur.next = cur.next.next;
} }
|