LeetCode 203.移除链表元素
答案
public ListNode removeElements(ListNode head, int val) {
if (head == null) return head;
ListNode dummy = new ListNode(-1, head);
ListNode pre = dummy;
ListNode cur = head;
while (cur != null){
if (cur.val == val){
pre.next = cur.next;
} else {
pre = cur;
}
cur = cur.next;
}
return dummy.next;
}
LeetCode 707.设计链表
答案
class ListNode{
int val;
ListNode next,prev;
public ListNode(int val){
this.val = val;
}
}
class MyLinkedList {
int size;
ListNode head, tail;
public MyLinkedList() {
this.size = 0;
this.head = new ListNode(0);
this.tail = new ListNode(0);
head.next = tail;
tail.next = head;
}
public int get(int index) {
if (index < 0 || index >= size) {
return -1;
}
ListNode cur = this.head;
if (index > size / 2) {
cur = tail;
for (int i = 0; i < size - index; i++) {
cur = cur.prev;
}
} else {
cur = head;
for (int i = 0; i <= index; i++) {
cur = cur.next;
}
}
return cur.val;
}
public void addAtHead(int val) {
addAtIndex(0, val);
}
public void addAtTail(int val) {
addAtIndex(size, val);
}
public void addAtIndex(int index, int val) {
ListNode cur = this.head;
if (index > size) {
return;
}
size++;
//找到插入节点的前驱节点
ListNode pre = head;
for (int i = 0; i < index; i++) {
pre = pre.next;
}
ListNode Add = new ListNode(val);
Add.next = pre.next;
pre.next.prev = Add;
Add.prev = pre;
pre.next = Add;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= size) {
return;
}
size--;
if (index == 0){
head = head.next;
return;
}
ListNode pre = head;
for (int i = 0; i < index; i++) {
pre = pre.next;
}
pre.next.next.prev = pre;
pre.next = pre.next.next;
}
}
LeetCode 207.翻转链表
答案
public ListNode reverseList(ListNode head) {
if (head == null) return null;
ListNode pre = null;
ListNode cur = head;
ListNode temp = null;
while (cur != null){
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}