Day03 链表
一、203.移除链表元素
1.原题
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode h = new ListNode();
h.next = head;
ListNode cur = h;
while(cur != null){
while(cur.next != null && cur.next.val == val){
cur.next = cur.next.next;
}
cur = cur.next;
}
return h.next;
// while(head != null && head.val == val){
// head = head.next;
// }
// ListNode cur = head;
// while(cur != null){
// while(cur.next != null && cur.next.val == val){
// cur.next = cur.next.next;
// }
// cur = cur.next;
// }
// return head;
}
}
采用两种做法,来处理头结点
1、建立一个虚拟头结点,把其他结点都当做next结点处理
2、不建立虚拟头结点,需要对头结点进行特殊处理,找到第一个合法的头结点
内容处理:
使用两个嵌套的while循环
内层for循环:判断next结点是否复合条件进行next.next操作
外层for循环:判断链表是否到达末尾,并且每次循环让指针指向下一个结点
二、707.设计链表
1.原题
class MyLinkedList {
//size存储链表元素的个数
int size;
//虚拟头结点
ListNode head;
//初始化链表
public MyLinkedList() {
size = 0;
head = new ListNode(0);
}
//获取第index个节点的数值
public int get(int index) {
//如果index非法,返回-1
if (index < 0 || index >= size) {
return -1;
}
ListNode currentNode = head;
//包含一个虚拟头节点,所以查找第 index+1 个节点
for (int i = 0; i <= index; i++) {
currentNode = currentNode.next;
}
return currentNode.val;
}
//在链表最前面插入一个节点
public void addAtHead(int val) {
addAtIndex(0, val);
}
//在链表的最后插入一个节点
public void addAtTail(int val) {
addAtIndex(size, val);
}
// 在第 index 个节点之前插入一个新节点,例如index为0,那么新插入的节点为链表的新头节点。
// 如果 index 等于链表的长度,则说明是新插入的节点为链表的尾结点
// 如果 index 大于链表的长度,则返回空
public void addAtIndex(int index, int val) {
if (index > size) {
return;
}
if (index < 0) {
index = 0;
}
size++;
//找到要插入节点的前驱
ListNode pred = head;
for (int i = 0; i < index; i++) {
pred = pred.next;
}
ListNode toAdd = new ListNode(val);
toAdd.next = pred.next;
pred.next = toAdd;
}
//删除第index个节点
public void deleteAtIndex(int index) {
if (index < 0 || index >= size) {
return;
}
size--;
ListNode pred = head;
for (int i = 0; i < index; i++) {
pred = pred.next;
}
pred.next = pred.next.next;
}
}
class ListNode{
int val;
ListNode next;
ListNode(){
}
ListNode(int val){
this.val = val;
}
ListNode(int val,ListNode next){
this.val = val;
this.next = next;
}
}
此题是对链表概念的考察,无算法级别的难度。
三、707.设计链表
1.原题
class Solution {
public ListNode reverseList(ListNode head) {
// ListNode pre = null;
// ListNode cur = head;
// ListNode temp = null;
// while(cur != null){
// temp = cur.next;// 保存下一个节点
// cur.next = pre;
// pre = cur;
// cur = temp;
// }
// return pre;
}
}
反转链表的思路:记录上一个结点(pre),记录下一个结点(temp),操作结点的next指向上一个结点,操作结点变赋值给pre,自己变为temp;
// 递归
class Solution {
public ListNode reverseList(ListNode head) {
return reverse(null, head);
}
private ListNode reverse(ListNode prev, ListNode cur) {
if (cur == null) {
return prev;
}
ListNode temp = null;
temp = cur.next;// 先保存下一个节点
cur.next = prev;// 反转
// 更新prev、cur位置
// prev = cur;
// cur = temp;
return reverse(cur, temp);
}
使用递归调用,与前一方法类似。