707. Design Linked List #
题目 #
设计链表的实现。可以选择使用单链表或双链表。
在链表类中实现这些功能:
get(index)
:获取链表中第index
个节点的值。如果索引无效,则返回-1
。addAtHead(val)
:在链表的第一个元素之前添加一个值为val
的节点。插入后,新节点将成为链表的第一个节点。addAtTail(val)
:将值为val
的节点追加到链表的最后一个元素。addAtIndex(index,val)
:在链表中的第index
个节点之前添加值为val
的节点。如果index
等于链表的长度,则该节点将附加到链表的末尾。如果index
大于链表长度,则不会插入节点。如果index
小于0,则在头部插入节点。deleteAtIndex(index)
:如果索引index
有效,则删除链表中的第index
个节点。
思路 #
代码 #
public class ListNode {
public ListNode prev;
public ListNode next;
public int val;
public ListNode(ListNode prev, ListNode next, int val) {
this.prev = prev;
this.next = next;
this.val = val;
}
}
class MyLinkedList {
private ListNode sentinel;
private int size;
public MyLinkedList() {
this.sentinel = new ListNode(null, null, -1);
this.sentinel.prev = this.sentinel;
this.sentinel.next = this.sentinel;
this.size = 0;
}
public int get(int index) {
if (index < 0 || index >= this.size) return -1;
ListNode ptr = this.sentinel.next;
for (int i=0; i<index; i++) ptr = ptr.next;
return ptr.val;
}
public void addAtHead(int val) {
this.sentinel.next = new ListNode(this.sentinel, this.sentinel.next, val);
this.sentinel.next.next.prev = this.sentinel.next;
this.size += 1;
}
public void addAtTail(int val) {
this.sentinel.prev = new ListNode(this.sentinel.prev, this.sentinel, val);
this.sentinel.prev.prev.next = this.sentinel.pre;
this.size += 1;
}
public void addAtIndex(int index, int val) {
if (index <= 0) this.addAtHead(val);
else if (index == this.size) this.addAtTail(val);
else if (index > 0 && index < this.size) {
ListNode ptr = this.sentinel;
for (int i=0; i<index; i++) ptr = ptr.next;
ptr.next = new ListNode(ptr, ptr.next, val);
ptr.next.next.prev = ptr.next;
this.size += 1;
}
}
public void deleteAtIndex(int index) {
if (index == 0) {
this.sentinel.next = this.sentinel.next.next;
this.sentinel.next.prev = this.sentinel;
this.size -= 1;
}
else if (index == this.size - 1) {
this.sentinel.prev = this.sentinel.prev.prev;
this.sentinel.prev.next = this.sentinel;
this.size -= 1;
}
else if (index > 0 && index < this.size - 1) {
ListNode ptr = this.sentinel;
for (int i=0; i<index; i++) ptr = ptr.next;
ptr.next = ptr.next.next;
ptr.next.prev = ptr;
this.size -= 1;
}
}
}