自己写一个简单的LinkedList
单链表
推荐阅读:https://www.cnblogs.com/zwtblog/tag/源码/
- 哨兵节点:
哨兵节点在树和链表中被广泛用作伪头、伪尾等,通常不保存任何数据。
我们将使用伪头来简化我们简化插入和删除。
class ListNode {
int val;
ListNode next;
ListNode() {
}
/**
* @param val
*/
ListNode(int val) {
this.val = val;
}
/**
* @param val
* @param next
*/
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
/**
* MyLinkedList
*/
class MyLinkedList {
int size;
ListNode head; //虚节点
public MyLinkedList() {
size = 0;
head = new ListNode(0);
}
/**
* @param index
* @return
*/
public int get(int index) {
if (index < 0 || index >= size) {
return -1;
}
ListNode cur = head;
for (int i = 0; i < index + 1; i++) {
cur = cur.next;
}
return cur.val;
}
/**
* @param val
*/
public void addAtHead(int val) {
addAtIndex(0, val);
}
/**
* @param val
*/
public void addAtTail(int val) {
addAtIndex(size, val);
}
/**
* @param index
* @param val
*/
public void addAtIndex(int index, int val) {
if (index > size) return;
if (index < 0) index = 0;
size++;
ListNode pre = head;
for (int i = 0; i < index; i++) {
pre = pre.next;
}
ListNode add = new ListNode(val);
add.next = pre.next;
pre.next = add;
}
/**
* @param index
*/
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 class LC707 {
public static void main(String[] args) {
MyLinkedList linkedList = new MyLinkedList();
linkedList.addAtHead(1);
linkedList.addAtTail(3);
linkedList.addAtIndex(1, 2); //链表变为1-> 2-> 3
System.out.println(linkedList.get(1)); //返回2
linkedList.deleteAtIndex(1); //现在链表是1-> 3
System.out.println(linkedList.get(1)); //返回3
}
}