題目描述:
設計鏈表的實現(xiàn)。您可以選擇使用單鏈表或雙鏈表版保。單鏈表中的節(jié)點應該具有兩個屬性:val 和 next呜笑。val 是當前節(jié)點的值夫否,next 是指向下一個節(jié)點的指針/引用。如果要使用雙向鏈表叫胁,則還需要一個屬性 prev 以指示鏈表中的上一個節(jié)點凰慈。假設鏈表中的所有節(jié)點都是 0-index 的。
在鏈表類中實現(xiàn)這些功能:
- get(index):獲取鏈表中第 index 個節(jié)點的值驼鹅。如果索引無效微谓,則返回-1。
- addAtHead(val):在鏈表的第一個元素之前添加一個值為 val 的節(jié)點输钩。插入后豺型,新節(jié)點將成為鏈表的第一個節(jié)點。
- addAtTail(val):將值為 val 的節(jié)點追加到鏈表的最后一個元素买乃。
- addAtIndex(index,val):在鏈表中的第 index 個節(jié)點之前添加值為 val 的節(jié)點姻氨。如果 index 等于鏈表的長度,則該節(jié)點將附加到鏈表的末尾剪验。如果 index 大于鏈表長度肴焊,則不會插入節(jié)點。
- deleteAtIndex(index):如果索引 index 有效功戚,則刪除鏈表中的第 index 個節(jié)點抖韩。
private class LinkNode{
public int val;
public LinkNode next;
public LinkNode(int val,LinkNode next){
this.val = val;
this.next = next;
}
}
private LinkNode dummyHeader;//虛擬頭結點
private int size; // 鏈表當前存儲個數(shù)
/** Initialize your data structure here. */
public MyLinkedList() {
this.size = 0;
this.dummyHeader = new LinkNode(0,null);
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
public int get(int index) {
if(index < 0 || index >= size ){
return -1;
}else{
LinkNode cur = dummyHeader.next;
for(int i = 0; i < index; i++){
cur = cur.next;
}
return cur.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. */
public void addAtHead(int val) {
addAtIndex(0,val);
}
/** Append a node of value val to the last element of the linked list. */
public void addAtTail(int val) {
addAtIndex(size,val);
}
/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
public void addAtIndex(int index, int val) {
if(index < 0 || index > size){
// throw new IllegalArgumentException("index is illegal");
}else{
LinkNode pre = dummyHeader;
for(int i = 0; i< index; i++){
pre = pre.next;
}
LinkNode insertNode = new LinkNode(val,null);
insertNode.next = pre.next;
pre.next = insertNode;
size++;
}
}
/** Delete the index-th node in the linked list, if the index is valid. */
public void deleteAtIndex(int index) {
if(index < 0 || index >=size || size == 0){
// throw new IllegalArgumentException("index is illegal");
return;
}
LinkNode pre = dummyHeader;
for(int i = 0; i < index; i++){
pre = pre.next;
}
LinkNode delNode = pre.next;
pre.next = delNode.next;
delNode = null;
size--;
}
}