Q17 LeetCode707 設計連結串列

清川1發表於2024-06-08

 1 class MyLinkedList {
 2     int size;
 3     ListNode head;
 4 
 5     public MyLinkedList() {
 6         size = 0;
 7         head = new ListNode(0);
 8     }
 9 
10     public int get(int index) {
11         if (index < 0 || index >= size) {
12             return -1;
13         }
14         ListNode cur = head;
15         for (int i = 0; i <= index; i++) {
16             cur = cur.next;
17         }
18         return cur.val;
19     }
20 
21     public void addAtHead(int val) {
22         addAtIndex(0, val);
23     }
24 
25     public void addAtTail(int val) {
26         addAtIndex(size, val);
27     }
28 
29     public void addAtIndex(int index, int val) {
30         if (index > size) {
31             return;
32         }
33         index = Math.max(0, index);
34         size++;
35         ListNode pred = head;
36         for (int i = 0; i < index; i++) {
37             pred = pred.next;
38         }
39         ListNode toAdd = new ListNode(val);
40         toAdd.next = pred.next;
41         pred.next = toAdd;
42     }
43 
44     public void deleteAtIndex(int index) {
45         if (index < 0 || index >= size) {
46             return;
47         }
48         size--;
49         ListNode pred = head;
50         for (int i = 0; i < index; i++) {
51             pred = pred.next;
52         }
53         pred.next = pred.next.next;
54     }
55 }
56 
57 class ListNode {
58     int val;
59     ListNode next;
60 
61     public ListNode(int val) {
62         this.val = val;
63     }
64 }

相關文章