代码随想录算法训练营第3天| 203.移除链表元素, 707.设计链表, 206.反转链表
203.移除链表元素
自己看到题目的第一想法
Very simple delete operation of linkedlist. The technique is creating a dummyHead in front of the linkedlist, so that deleting the head is the same as deleting the other node.
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(-1);
ListNode ans = dummy;
dummy.next = head;
while (dummy != null) {
if (dummy.next != null && dummy.next.val == val) {
dummy.next = dummy.next.next;
continue;
}
dummy = dummy.next;
}
return ans.next;
}
}
707.设计链表
自己看到题目的第一想法
This question tested my understanding of the major operations of a linkedlist. The difficult point for me is addAtIndex and deleteAtIndex. The key here is I need to find the Node before the index in order to insert or delete the Node.
class MyLinkedList {
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
this.next = null;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
ListNode dummyHead;
public MyLinkedList() {
this.dummyHead = new ListNode(-1);
}
public int get(int index) {
if (dummyHead.next == null) {
return -1;
}
ListNode cur = dummyHead.next;
int count = 0;
while (cur != null) {
if (index == count) {
return cur.val;
}
count++;
cur = cur.next;
}
return -1;
}
public void addAtHead(int val) {
ListNode headNext = dummyHead.next;
dummyHead.next = new ListNode(val, headNext);
}
public void addAtTail(int val) {
ListNode cur = this.dummyHead;
while (cur.next != null) {
cur = cur.next;
}
cur.next = new ListNode(val);
}
public void addAtIndex(int index, int val) {
ListNode cur = dummyHead;
int nextIdx = 0;
while (cur.next != null) {
if (nextIdx == index) {
ListNode nextnext = cur.next;
cur.next = new ListNode(val, nextnext);
return;
}
nextIdx++;
cur = cur.next;
}
if (nextIdx == index) {
cur.next = new ListNode(val);
}
}
public void deleteAtIndex(int index) {
int count = 0;
ListNode cur = dummyHead;
while (cur != null && cur.next != null) {
if (count == index) {
cur.next = cur.next.next;
}
cur = cur.next;
count++;
}
}
}
206.反转链表
自己看到题目的第一想法
Just some manipulation of pointer in linkedlist, can be done in 1 pass.
class Solution {
public ListNode reverseList(ListNode head) {
ListNode end = null;
ListNode cur = head;
while (cur != null) {
ListNode curNext = cur.next;
cur.next = end;
end = cur;
cur = curNext;
}
return end;
}
}