要点⭐
链表的常见操作
获取第n个节点的值
头部插入节点
尾部插入节点
第n个节点前插入(先立新,在破旧)
删除第n个节点
class ListNode{
int val;
ListNode next;
ListNode(){};
ListNode(int val){
this.val=val;
}
}
class MyLinkedList {
//链表大小
int size;
//虚拟头节点
ListNode head;
//初始化链表
public MyLinkedList(){
size=0;
head=new ListNode(0);
}
public int get(int index) {
if(index<0||index>=size){
return -1;
}
ListNode currentNode=head;
//包含一个虚拟头节点,所以查找第index+1个节点
for(int i=0;i<=index;i++){
currentNode=currentNode.next;
}
return currentNode.val;
}
public void addAtHead(int val) {
ListNode newNode=new ListNode(val);
newNode.next=head.next;
head.next=newNode;
size++;
}
public void addAtTail(int val) {
ListNode newNode=new ListNode(val);
ListNode currentNode=head;
while(currentNode.next!=null){
currentNode=currentNode.next;
}
currentNode.next=newNode;
size++;
}
public void addAtIndex(int index, int val) {
if(index>size){
return;
}
if(index<0){
index=0;
}
size++;
ListNode pred=head;
for(int i=0;i<index;i++){
pred=pred.next;
}
ListNode toAdd=new ListNode(val);
toAdd.next=pred.next;
pred.next=toAdd;
}
public void deleteAtIndex(int index) {
if(index<0||index>=size){
return;
}
size--;
ListNode pred=head;
for(int i=0;i<index;i++){
pred=pred.next;
}
pred.next=pred.next.next;
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList obj = new MyLinkedList();
* int param_1 = obj.get(index);
* obj.addAtHead(val);
* obj.addAtTail(val);
* obj.addAtIndex(index,val);
* obj.deleteAtIndex(index);
*/