自己写的设计链表测试过了,但是执行出错,麻烦看一下哪错了,谢谢
class ListNode{
int val;
ListNode next;
ListNode(){}
ListNode(int val){this.val = val;}
ListNode(int val,ListNode next){this.val = val;this.next = next;}
}
class MyLinkedList {
ListNode head;
public MyLinkedList() {
//定义虚拟头节点
this.head = new ListNode(0);
}
public int get(int index) {
ListNode cur = head;
while(index != 0){
cur = cur.next;
index--;
}
return cur.next.val;
}
public void addAtHead(int val) {
ListNode newNode = new ListNode(val);
newNode.next = head.next;
head.next = newNode;
}
public void addAtTail(int val) {
ListNode cur = head;
ListNode newNode = new ListNode(val);
while(cur.next != null){
cur = cur.next;
}
cur.next = newNode;
}
public void addAtIndex(int index, int val) {
ListNode cur = head;
ListNode newNode = new ListNode(val);
while(index != 0){
cur = cur.next;
index--;
}
newNode.next = cur.next;
cur.next = newNode;
}
public void deleteAtIndex(int index) {
ListNode cur = head;
while(index != 0){
cur = cur.next;
index--;
}
cur.next = cur.next.next;
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList obj = new MyLinkedList();
* int param_1 = obj.get(index);
* obj.addAtHead(val);
* obj.addAtTail(val);
* obj.addAtIndex(index,val);
* obj.deleteAtIndex(index);
*/