package ListNode03;
import java.util.LinkedList;
import java.util.List;
class MyLinkedList {
//计算单链表的长短,根据addAtIndex添加时计算
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 cur = head;
for (int i=0;i<=index;i++){
cur = cur.next;
}
return cur.val;
}
public void addAtHead(int val) {
addAtIndex(0,val);
}
public void addAtTail(int val) {
addAtIndex(size,val);
}
public void addAtIndex(int index, int val) {
if (index > size){
return;
}
index = Math.max(0,index);
size++;
ListNode pre = head;
for (int i=0;i<index;i++){
pre = pre.next;
}
ListNode listNode = new ListNode(val);
listNode.next = pre.next;
pre.next = listNode;
}
public void deleteAtIndex(int index) {
if (index<0 || index >= size){
return;
}
size--;
ListNode pre = head;
for (int i=0;i<index;i++){
pre = pre.next;
}
pre.next = pre.next.next;
}
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
list.addAtIndex(0,1);
list.addAtIndex(1,2);
System.out.println(list.get(0));
System.out.println(list.get(1));
list.deleteAtIndex(0);
System.out.println(list.get(0));
}
}
class ListNode{
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
设计链表,实现链表功能
最新推荐文章于 2024-08-18 21:36:31 发布