Day3 链表 part1
链表定义
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;
}
}
Time Complexity
Type | add/delete | search |
---|---|---|
Array | O(n) | O(1) |
LinkedList | O(1) | O(n) |
Leetcode203 Remove Linked List Elements
题目链接
利用虚拟头结点
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) return null;
ListNode dummy = new ListNode(-1, head);
ListNode p = dummy;
ListNode cur = head;
while(cur != null){
if (cur.val == val){
p.next = cur.next;
}
else{
p = cur;
}
cur = cur.next;
}
return dummy.next;
}
}
Leetcode707 Design Linked List
class MyLinkedList {
int size;
// 虚拟头结点
ListNode dummy;
public MyLinkedList() {
size = 0;
dummy = new ListNode(-1);
}
public int get(int index) {
if (index < 0 || index >= size) return -1;
ListNode cur = dummy;
for (int i = 0; i < index + 1; 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) {
if (index > size) return;
if (index < 0){
index = 0;
}
size++;
ListNode prev = dummy;
for (int i = 0; i < index; i++){
prev = prev.next;
}
ListNode cur = new ListNode(val);
cur.next = prev.next;
prev.next = cur;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= size) return;
size--;
if (index == 0) {
dummy = dummy.next;
return;
}
ListNode prev = dummy;
for (int i = 0; i < index; i++){
prev = prev.next;
}
prev.next = prev.next.next;
}
}
class ListNode{
int val;
ListNode next;
ListNode(){}
ListNode(int val){
this.val = val;
}
}
Leetcode206 Reverse Linked List
Method1 stack
public ListNode reverseList(ListNode head) {
if (head == null) return null;
ListNode dummy = new ListNode(-1), p = dummy;
Stack<ListNode> stack = new Stack<>();
while(head != null){
stack.push(head);
head = head.next;
}
while(!stack.empty()){
p.next = stack.pop();
p = p.next;
}
p.next = null;
return dummy.next;
}
Method2 reverse
public ListNode reverseList(ListNode head) {
ListNode cur = null, nex = head;
while (nex != null){
ListNode tmp = nex.next;
nex.next = cur;
cur = nex;
nex = tmp;
}
return cur;
}