203:
主要是学习了如何使用一个虚拟点(temp),这样不需要单独写一段来看最开始的节点是不是等于val。
Code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null){
return head;
}
ListNode temp = new ListNode(-1, head);
ListNode previous = temp;
ListNode current = head;
while(current != null){
if(current.val == val){
previous.next = current.next;
current = current.next;
}
else if(current.val != val){
previous = current;
current = current.next;
}
}
return temp.next;
}
}
用时:30min
707:
暂时还没有用虚拟node(后面再研究一下)
Code:
class MyLinkedList {
Node head;
int length;
public class Node{
int val;
Node next;
Node(int val){
this.val = val;
}
}
public MyLinkedList() {
this.head = null;
this.length = 0;
}
public int get(int index) {
if(index < 0 || index >= length){
return -1;
}
Node current = head;
while(index != 0){
current = current.next;
index--;
}
return current.val;
}
public void addAtHead(int val) {
Node newhead = new Node(val);
newhead.next = head;
head = newhead;
length++;
}
public void addAtTail(int val) {
if(head == null){
addAtHead(val);
}
else{
Node current = head;
while(current.next != null){
current = current.next;
}
Node newtail = new Node(val);
current.next = newtail;
length++;
}
}
public void addAtIndex(int index, int val) {
if(index > length){
return;
}
if(index == 0){
addAtHead(val);
}else{
int counter = 1;
Node temp = head;
while(counter < index){
temp = temp.next;
counter++;
}
Node newadd = new Node(val);
Node next = temp.next;
temp.next = newadd;
newadd.next = next;
length++;
}
}
public void deleteAtIndex(int index) {
if(index >= length){
return;
}
else if(index == 0){
head = head.next;
length--;
}else{
int counter = 1;
Node current = head;
while(counter < index){
current = current.next;
counter++;
}
current.next = current.next.next;
length--;
}
}
}
/**
* 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);
*/
206:
Code: 掌握了双指针的思路,不需要在建一个linked list消耗内存,只需要用previous 和 current调转就好。重点是如何初始化previous!
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode current = head;
ListNode previous = null;
while(current != null){
ListNode nextelement = current.next;
current.next = previous;
previous = current;
current = nextelement;
}
return previous;
}
}
用时:20min