707. 设计链表
用dummy_head操作方便很多
public class MyLinkedList {
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
ListNode dummy_head;
int size;
public MyLinkedList() {
size = 0;
dummy_head = new ListNode(-1);
}
public int get(int index) {
if (size == 0 || index < 0 || index >= size)
return -1;
ListNode node = dummy_head;
for (int i = 0; i <= index; i++) {
node = node.next;
}
return node.val;
}
public void addAtHead(int val) {
addAtIndex(0, val);
}
public void addAtTail(int val) {
addAtIndex(size, val);
}
public void addAtIndex(int index, int val) {
if (index > size) return;
if (index < 0) index = 0;
size++;
ListNode preNode = dummy_head;
for (int i = 0; i < index; i++) {
preNode = preNode.next;
}
ListNode addNode = new ListNode(val);
addNode.next = preNode.next;
preNode.next = addNode;
}
public void deleteAtIndex(int index) {
if (index < 0 || size == 0 || index >= size)
return;
size--;
ListNode prevNode = dummy_head;
for (int i = 0; i < index; i++) {
prevNode = prevNode.next;
}
ListNode deleteNode = prevNode.next;
prevNode.next = deleteNode.next;
deleteNode.next = null;
}
}
206. 反转链表
注意点:p点、c点、n点何时赋新值,避免空指针异常,尤其是n的赋值
public ListNode reverseList(ListNode head) {
if (head == null)
return head;
ListNode p = null;
ListNode c = head;
ListNode n = null;
while (c!=null){
n = c.next;
c.next = p;
p = c;
c = n;
}
return p;
}