移除链表元素
题目
给你一个链表的头节点 head
和一个整数 val
,请你删除链表中所有满足 Node.val == val
的节点,并返回 新的头节点 。
解析
链表删除元素,需要考虑有没有头指针。没有头指针就需要考虑头节点和非头节点,需要把头节点单独拿出来处理。有头指针的所有结点的操作都一样。
Java代码实现
没有头指针解法
public static ListNode handle(ListNode head, int val) {
while (head != null && head.val == val) {
head = head.next;
}
if (head == null) {
return null;
}
ListNode cur = head;
while (cur != null && cur.next != null) {
int value = cur.next.val;
if (val == value) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
手动增加虚拟头指针
public static ListNode handle(ListNode head, int val) {
ListNode dummy = new ListNode();
dummy.next = head;
ListNode cur = dummy;
while (cur.next != null) {
if (cur.next.val == val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return dummy.next;
}
设计链表
题目
你可以选择使用单链表或者双链表,设计并实现自己的链表。
解析
需要实现获取链表中的节点,删除,添加功能。
Java代码实现
public class ListNode {
int val;
ListNode next;
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
@Override
public String toString() {
return "LinkedListNode{" +
"val=" + val +
", next=" + next +
'}';
}
}
public static class MyLinkedList {
int size;
// 头指针,虚拟头节点
ListNode head;
public MyLinkedList() {
int size = 0;
head = new ListNode();
}
public int get(int index) {
if (index < 0 || index >= size) {
return -1;
}
ListNode cur = head;
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;
}
ListNode pre = head;
for (int i = 0; i < index; i++) {
pre = pre.next;
}
ListNode listNode = new ListNode(val);
listNode.next = pre.next;
pre.next = listNode;
size++;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= size) {
return;
}
ListNode pre = head;
for (int i = 0; i < index; i++) {
pre = pre.next;
}
pre.next = pre.next.next;
size--;
}
}
反转链表
题目
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
解析
头插法可以反转链表,但是在新建一个链表会比较浪费内存空间,所以有个指针逆置的方法可以是实现链表反转,并且节约内存空间。需要定义两个指针,一个指向当前节点,一个指向当前节点的前一个结点。
Java代码实现
public static ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode temp;
while (cur != null) {
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}