DAY03 目录
前言
- 学得好慢噢,赶不上进度了快
- 设计链表中,deleteAtIndex中,if的index > size判断,着了它的道
- Python, 我的Python
203.移除链表元素
虚拟头结点
/**
* 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; }
* }
*/
//从头结点往后走,判断val
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(0, 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;
}
}
707.设计链表
保证cur指向正确,可考虑极端情况,如index=0时
class MyLinkedList {
int size;
ListNode dummy;
public MyLinkedList() {
dummy = new ListNode(-1);
size = 0;
// ListNode n1 = new ListNode(9);
dummy.next = ;//不写也可以
// dummy.next = n1;
}
public int get(int index) {
ListNode cur = dummy;
if (index < 0 || index > size - 1) {
return -1;
}
while (index-- > 0) {
cur = cur.next;
}
return cur.next.val;
}
public void addAtHead(int val) {
// ListNode temp = new ListNode(val);
// ListNode cur = dummy;
// temp.next = cur.next;
// cur.next = temp;
// size++;
addAtIndex(0,val);//调用addAtIndex函数
}
public void addAtTail(int val) {
// ListNode temp = new ListNode(val);
// ListNode cur = dummy;
// while (cur.next != null) {
// cur = cur.next;
// }
// cur.next = temp;
// size++;
addAtIndex(size,val);//调用addAtIndex函数
}
public void addAtIndex(int index, int val) {
if (index < 0 || index > size) {//此处考虑在末尾添加的情况
return;
}
ListNode temp = new ListNode(val);
ListNode cur = dummy;
//保证第n个节点指向cur.next
while (index-- > 0) {
cur = cur.next;
}
temp.next = cur.next;
cur.next = temp;
size++;
}
public void deleteAtIndex(int index) {
if (index < 0 || index > size - 1) {
return;
}
ListNode cur = dummy;
while (index-- > 0) {
cur = cur.next;
}
cur.next = cur.next.next;
size--;
}
}
206.反转链表
双指针
class Solution {
public ListNode reverseList(ListNode head) {
// ListNode dummy = new ListNode(-1, head);没必要
ListNode cur = head;
ListNode pre = null;
ListNode temp;//通过之后试一试不初始化可不可以
while (cur != null) {
temp = cur.next;//因为此处有赋值,所以不初始化可以
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
return reverse(null, head);
}
}
递归 (先写出双指针,再演变,非必要的话不主动写递归)
class Solution {
public ListNode reverse(ListNode pre, ListNode cur) {//参数对吗,还是用两个参数
// ListNode temp = cur.next;报错,cur是null,没有next
if (cur == null) {//所以要放在前面
return pre;
}
ListNode temp = cur.next;
cur.next = pre;
return reverse(cur, temp);
}
public ListNode reverseList(ListNode head) {
return reverse(null, head);
}
}