关于leetcode707题的链表设计问题
来源:5-5 不仅仅是穿针引线 Delete Node in a Linked List
v不离不弃v
2020-06-04
今天做了这一题,完全是按照您数据结构那章节的创建属于我们自己的链表的代码写的,头结点采用dummyhead,但是测试案例中每次进行delete的时候总有index超出范围,所以就有点无语,不知道这个题目是怎么约束size的,老师有空可以帮我看看问题出在哪里呢?
class MyLinkedList {
private class ListNode{
public int val;
public ListNode next;
public ListNode(int val){this.val = val;}
}
/** Initialize your data structure here. */
private int size;
private ListNode dummyHead;
public MyLinkedList() {
size = 0;
dummyHead = new ListNode(- 1);
}
/** 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 < 0 || index >= size) return - 1;
ListNode cur = dummyHead.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) {
ListNode node = new ListNode(val);
node.next = dummyHead.next;
dummyHead.next = node;
size ++;
}
/** Append a node of value val to the last element of the linked list. */
public void addAtTail(int val) {
ListNode pre = dummyHead;
for(int i = 0; i < size; i ++)
pre = pre.next;
ListNode node = new ListNode(val);
node.next = pre.next;
pre.next = 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 < 0 || index > size)
throw new IllegalArgumentException("Add failed! Illegal index!");
ListNode pre = dummyHead;
for(int i = 0; i < index; i ++)
pre = pre.next;
ListNode node = new ListNode(val);
node.next = pre.next;
pre.next = node;
size ++;
}
/** Delete the index-th node in the linked list, if the index is valid. */
public void deleteAtIndex(int index) {
if(index < 0 || index >= size)
throw new IllegalArgumentException("Remove failed! Index is illegal!");
ListNode pre = dummyHead;
for(int i = 0; i < index; i ++)
pre = pre.next;
ListNode delNode = pre.next;
pre.next = delNode.next;
delNode.next = null;
size --;
}
}
/**
* 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);
*/
写回答
1回答
-
liuyubobobo
2020-06-04
Solution 类呢?请每次给我可以运行调试的代码。
042020-06-04
相似问题