问题: 在尾插法创建链表时,找到最后一个结点,我感觉找到的是最后一个结点,但是提示空指针异常 题目链接: LeetCode 707: 设计链表
我写的代码:
class ListNode{
int val;
ListNode next;
public 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 current = head;
for(int i = 0; i <= index; i++){
current = current.next;
}
return current.val;
}
public void addAtHead(int val) {
ListNode node = new ListNode(val);
node.next = head.next;
head.next = node;
size++;
}
public void addAtTail(int val) {
ListNode node = new ListNode(val);
ListNode q = head;
for(int i = 0; i < size; i++){
q = q.next;
}
node.next = q.next;
q.next = node;
size++;
}
public void addAtIndex(int index, int val) {
if(index > size){
return;
}
if(index < 0){
addAtHead(val);
}else if(index == size){
addAtTail(val);
}else{
ListNode node = new ListNode(val);
ListNode p = head;
for(int i = 0; i < index; i++){
p = p.next;
}
node.next = p.next;
p.next = node;
size++;
}
}
public void deleteAtIndex(int index) {
if(index < 0 || index >= size){
return;
}
ListNode p = head;
for(int i = 0; i < index; i++){
p = p.next;
}
if(p.next != null){
p.next = p.next.next;
}
}
}
|