203.移除链表元素 707.设计链表 206.反转链表
一、 203.移除链表元素
题意:删除链表中等于给定值 val 的所有节点。
示例 1: 输入:head = [1,2,6,3,4,5,6], val = 6 输出:[1,2,3,4,5]
示例 2: 输入:head = [], val = 1 输出:[]
示例 3: 输入:head = [7,7,7,7], val = 7 输出:[]
代码如下(示例):注意使用虚拟头结点。删除结点时,一定要知道他的前置节点。
class Solution {
//添加虚拟头节点
public ListNode removeElements(ListNode head, int val) {
if (head == null){
return head;
}
//设置头结点
ListNode dummy = new ListNode(-1, head);
//设置preNode节点
ListNode pre = dummy;
ListNode curr = head;
while (curr != null){
if (curr.val == val){
pre.next = curr.next;
}else{
pre = curr;
}
curr = curr.next;
}
return dummy.next;
}
}
二、 707.设计链表
题意:
在链表类中实现这些功能:
get(index):获取链表中第 index 个节点的值。如果索引无效,则返回-1。
addAtHead(val):在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。
addAtTail(val):将值为 val 的节点追加到链表的最后一个元素。
addAtIndex(index,val):在链表中的第 index 个节点之前添加值为 val 的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。如果index小于0,则在头部插入节点。
deleteAtIndex(index):如果索引 index 有效,则删除链表中的第 index 个节点。
class MyLinkedList {
//size存储链表元素的个数
int size;
//虚拟头结点
ListNode head;
public MyLinkedList() {
size = 0;
head = new ListNode(0);
}
//获取第index个节点的数值,注意index是从0开始的,第0个节点就是头结点
public int get(int index) {
//若index非法
if (index < 0 || index >= size) return -1;
ListNode cur = head;
//包含一个头结点,所以要找第index+1个节点
for (int i = 0; i <= index; 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;
}
ListNode node = new ListNode(val);
ListNode pre = head;
//知道第index值的前驱节点
for (int i = 0; i < index; i++){
pre = pre.next;
}
node.next = pre.next;
pre.next = node;
size++;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= size) {
return;
}
size--;
if (index == 0) {
head = head.next;
return;
}
ListNode pre = head;
for (int i = 0; i < index ; i++) {
pre = pre.next;
}
pre.next = pre.next.next;
}
}
206.反转链表
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) return null;
if (head.next == null) return head;
ListNode pre = null;
ListNode cur = head;
ListNode aft = null;
while (cur != null){
aft = cur.next;
cur.next = pre;
pre = cur;
cur = aft;
}
return pre;
}
}
总结
今天是对链表的操作、一定要注意操作链表的节点时,要知道他的上一个节点。学会使用虚拟头结点。