My LeetCode Diary - Day3 LinkedList
203. Remove Linked List Elements
/**
* 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) {
// [1,1,1,1,1,1,1]
while (head != null && head.val == val){
head = head.next;
}
ListNode cur = head;
while (cur!=null && cur.next!=null){
if(cur.next.val == val){
cur.next=cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
}
206. Reverse Linked List
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode cur = head;
ListNode temp = null;
while (cur != null) {
temp = cur.next;
cur.next = prev;
prev = cur;
cur = temp;
}
return prev;
}
}
707. Design Linked List
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 >= length)
return -1;
int counter = 0;
Node temp = head;
while(counter < index) {
counter++;
temp = temp.next;
}
return temp.val;
}
public void addAtHead(int val) {
Node newnew = new Node(val);
newnew.next = head;
head = newnew;
length++;
}
public void addAtTail(int val) {
if(head == null) {
addAtHead(val);
}else {
Node temp = head;
while(temp.next != null)
temp = temp.next;
Node newnew = new Node(val);
temp.next = newnew;
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 newnew = new Node(val);
Node next = temp.next;
temp.next = newnew;
newnew.next = next;
length++;
}
}
public void deleteAtIndex(int index) {
if(index >= length)
return;
if(index == 0) {
head = head.next;
length--;
}else {
int counter = 1;
Node temp = head;
while(counter < index) {
counter++;
temp = temp.next;
}
temp.next = temp.next.next;
length--;
}
}
}