Difficulty :
Medium
Java
演算法Algorithm
撰寫人KVJK_2125Fri, Mar 29, 2024 22:07
Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: val
and next
. val
is the value of the current node, and next
is a pointer/reference to the next node.
If you want to use the doubly linked list, you will need one more attribute prev
to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.
Implement the MyLinkedList
class:
MyLinkedList()
Initializes the MyLinkedList
object.int get(int index)
Get the value of the index th
node in the linked list. If the index is invalid, return -1
.void addAtHead(int val)
Add a node of value val
before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.void addAtTail(int val)
Append a node of value val
as the last element of the linked list.void addAtIndex(int index, int val)
Add a node of value val
before the index th
node in the linked list. If index
equals the length of the linked list, the node will be appended to the end of the linked list. If index
is greater than the length, the node will not be inserted.void deleteAtIndex(int index)
Delete the index th
node in the linked list, if the index is valid.Example 1:
Input
["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"]
[[], [1], [3], [1, 2], [1], [1], [1]]
Output
[null, null, null, null, 2, null, 3]
Explanation
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.addAtHead(1);
myLinkedList.addAtTail(3);
myLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3
myLinkedList.get(1); // return 2
myLinkedList.deleteAtIndex(1); // now the linked list is 1->3
myLinkedList.get(1); // return 3
0 <= index, val <= 1000
get
, addAtHead
, addAtTail
, addAtIndex
and deleteAtIndex
.以Example 1做解釋:
Step1.
先建立一個class Node
,其中建立val
存放值,next
指向下一個node
Step2.
在MyLinkedList
中,建立一個空指標Node head = null
,以及一個變數紀錄資料長度int bruh = 0
Step3.整理函式內容
– MyLinkedList():初始化。
– get(index):
先判斷index是否有效(是否超出長度,或是否小於0)index >= bruh || index < 0
,否則回傳-1
。
有效則建立一個新節點Node headtmp = head
,在執行index
次內,指向next
,在最後回傳值。
– addAtHead(val):
建立一個新節點Node veHead = new Node(val)
,將veHead.next
指向head
,再把head
指向vehead
,這樣就把新節點放入最前面了。
在最後長度記得加1bruh++
。
– addAtTail(val):
先判斷head是否為空(head == null ?
)。
若為空的話,直接將val
加入list即可(head = new Node(val)
);
若不為空,則建立一個指向head
的新節點Node headtmp = head
。直到next
為空(null
)之前,將新建的node指向next
。
最後一個next
指向val
使其成為最後一個元素。
在最後長度記得加1bruh++
。
– addAtIndex(index, val):有點亂,我用寫的。
–addAtDelete(index):
先判斷index是否有效(是否超出長度,或是否小於0)index >= bruh || index < 0
,
有效的話,建立一個指向head
的新節點Node current = head
,在建立一個指向空null
的新節點Node previous = null
。
在執行index次內,指向next
。
結束後,若previous == null
,則將head
指向next
;若previous!=null
,則略過current
,讓previous.next
指向current.next
,即刪除current
。
在最後長度記得減1bruh--
。