Question 707 Design Linked List
class ListNode {
ListNode next;
int value;
public ListNode(int value) {
this.value = value;
}
public ListNode(int value, ListNode node) {
this.next = node;
this.value = value;
}
}
class MyLinkedList {
ListNode head;
int count;
public MyLinkedList() {
}
//一开始用来debug的函数
public void showList() {
ListNode tmp = head;
while (tmp != null) {
System.out.printf("%d -> ", tmp.value);
tmp = tmp.next;
}
}
public int get(int index) {
if (index < 0 || index >= count) {
return -1;
}
int i = 0;
ListNode tmp = head;
while (tmp != null) {
if (i == index) {
return tmp.value;
}
i++;
tmp = tmp.next;
}
//showList();
return -100;
}
public void addAtHead(int val) {
if (count == 0) {
this.head = new ListNode(val);
} else {
ListNode newNode = new ListNode(val, this.head);
this.head = newNode;
}
count++;
//showList();
}
public void addAtTail(int val) {
if (count == 0) {
this.head = new ListNode(val);
} else {
ListNode tmp = head;
while (tmp.next != null) {
tmp = tmp.next;
}
tmp.next = new ListNode(val);
}
count++;
//showList();
}
public void addAtIndex(int index, int val) {
if (index > count) {
return;
}
int i = 0;
ListNode tmp = head;
if (index == 0) {
ListNode newNode = new ListNode(val, head);
this.head = newNode;
} else {
while (i < index - 1) {
tmp = tmp.next;
i++;
}
ListNode newNode = new ListNode(val, tmp.next);
tmp.next = newNode;
}
//showList();
count++;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= count) {
return;
}
if (index == 0) {
this.head = this.head.next;
} else {
int i = 0;
ListNode tmp = head;
while(i < index - 1) {
i++;
tmp = tmp.next;
}
tmp.next = tmp.next.next;
}
count--;
}
}
/**
* 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);
*/
t(index);
- obj.addAtHead(val);
- obj.addAtTail(val);
- obj.addAtIndex(index,val);
- obj.deleteAtIndex(index);
*/
``
其实我个人认为这道题恶心就恶心在while循环中同时递增指针和变量i,这样的话非常容易出现过界的情况,另外就是head指针的修改,一定要注意。
用来避免上述情况的其实就是使用一个虚拟节点,但是那样的话对于边界的计算其实是比较复杂的。