# 题目描述

get(index)：获取链表中第 index 个节点的值。如果索引无效，则返回-1。
addAtIndex(index,val)：在链表中的第 index 个节点之前添加值为 val 的节点。如果 index 等于链表的长度，则该节点将附加到链表的末尾。如果 index 大于链表长度，则不会插入节点。如果index小于0，则在头部插入节点。
deleteAtIndex(index)：如果索引 index 有效，则删除链表中的第 index 个节点。

# 代码：

public class ListNode {
int val;
ListNode next;
ListNode(int x){val = x; }
}
int size;

/** Initialize your data structure here. */
size = 0;
//虚拟化一个头节点
ListNode newHead = new ListNode(0);
}

/** 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;
}
ListNode curr = head;
for(int i=0;i <= index ; i++){
curr = curr.next;
}
return curr.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. */
//直接写
ListNode newNode = new ListNode(val);

size++;

}

/** Append a node of value val to the last element of the linked list. */
public void addAtTail(int val) {
ListNode curr = head;
while (curr.next != null){
curr = curr.next;
}
ListNode newNode = new ListNode(val);
newNode.next = null;
curr.next = newNode;

size++;
}

/** 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 >size){return; }
if (index < 0){ index = 0;}

ListNode curr = head;
for(int i=0;i < index ; i++){
curr = curr.next;
}

ListNode newNode =new ListNode(val);
newNode.next = curr.next;
curr.next = newNode;

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) {return;}

ListNode curr = head;
for(int i=0;i < index; i++){
curr = curr.next;
}

curr.next = curr.next.next;
size--;

}
}

/**
* Your MyLinkedList object will be instantiated and called as such:
* int param_1 = obj.get(index);
* obj.deleteAtIndex(index);
*/


## 注意：

• 在删除指定下标的节点。index = size 无效；
• 增加/删除节点时，修改size;
• 虚拟化头节点的使用;

05-26 4134
02-18 33
09-23 77
01-04 128
09-07 48
04-02 118
05-05 68
06-14 174
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林