最近在学数据结构
学了java感觉看到链表表面上很是理解但是设计链表我表示很是困惑
class MyLinkedList {
private Node head;
private Node tail;
private int size;
private class Node {
int val;
Node next;
public Node() {
}
public Node(int val) {
this.val = val;
}
}
/** Initialize your data structure here. */
public MyLinkedList() {
}
/** 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 (head == null || index < 0 || index >= size) return -1;
Node temp = head;
while (index != 0 && temp.next != null) {
temp = temp.next;
index--;
}
return temp.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) {
Node node = new Node(val);
node.next = head;
if (head == null && tail == null) {
tail = node;
}
head = node;
size++;
}
/** Append a node of value val to the last element of the linked list. */
public void addAtTail(int val) {
Node node = new Node(val);
if (head == null && tail == null) {
head = tail = node;
}else {
tail.next = node;
tail = node;
}
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) addAtTail(val);
else if (index == 0) addAtHead(val);
else if (index > 0 && index < size) {
Node temp = head;
while (temp.next != null && index != 1) {
temp = temp.next;
index--;
}
Node node = new Node(val);
node.next = temp.next;
temp.next = node;
size++;
}
}
public void deleteHead() {
if (head != null) {
if (head.next == null) {
head = tail = null;
}else {
head = head.next;
}
size--;
}
}
/** Delete the index-th node in the linked list, if the index is valid. */
public void deleteAtIndex(int index) {
if (index == 0) deleteHead();
else if (index > 0 && index < size) {
Node temp = head;
while (temp.next != null && index != 1) {
index--;
temp = temp.next;
}
Node next = temp.next;
if (next.next == null) {
tail = temp;
}
temp.next = next.next;
size--;
}
}
}
我想问的是这个Node head Node next 是不是Node对象的一种定义类型,没有初始化,那就是null我想问下,这样是什么意思?具体什么含义,或者指教一下,熟悉那块知识点。
我知道很白这个问题,但是我真的迷
add新对象的时候才会初始化。