class ListNode {
int val;
ListNode next;
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
}
class MyLinkedList {
// 定义成员变量,构造函数
int size;
ListNode head;
public MyLinkedList() {
size = 0;
// 这里一定要给 head 初始化一个对象
head = new ListNode();
}
/** 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 < -1 || index > size - 1)return -1;
ListNode cur = head.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)return;
ListNode node = new ListNode(val);
ListNode pred = head;
for (int i = 0; i < index; i++) {
pred = pred.next;
}
node.next = pred.next;
pred.next = node;
size++;
}
/** Delete the index-th node in the linked list, if the index is valid. */
public void deleteAtIndex(int index) {
if(index < -1 || index > size)return;
ListNode pred = head;
for (int i = 0; i < index; i++) {
pred = pred.next;
}
pred.next = pred.next.next;
size--;
}
}
class test{
public static void main(String[] args) {
MyLinkedList mll = new MyLinkedList();
mll.addAtHead(3);
mll.addAtHead(2);
mll.addAtHead(1);
System.out.println(mll.size);
System.out.println(mll.get(0));
mll.deleteAtIndex(0);
System.out.println(mll.get(1));
}
}
链表-设计
最新推荐文章于 2024-09-06 16:47:20 发布