链表基础: 代码随想录
203.移除链表元素
题目链接: 力扣题目链接文章讲解: 力扣题目链接
代码:
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) return null;
ListNode lin = new ListNode(-1, head);
ListNode prev = lin;
ListNode cur = head;
while (cur != null) {
if (cur.val == val) {
prev.next = cur.next;
} else {
prev = cur;
}
cur = prev.next;
}
return lin.next;
}
}
707.设计链表
题目链接: 力扣题目链接文章讲解: 力扣题目链接
代码:
class MyLinkedListNode {
public int val;
public MyLinkedListNode next;
public MyLinkedListNode(int val, MyLinkedListNode next) {
this.val = val;
this.next = next;
}
}
class MyLinkedList {
private MyLinkedListNode head;
private MyLinkedListNode tail;
private int sum;
public MyLinkedList() {
this.head = null;
this.tail = null;
this.sum = 0;
}
public int get(int index) {
if (index >= sum) return -1;
MyLinkedListNode it = this.head;
for (; index > 0; index--) {
it = it.next;
}
return it.val;
}
public void addAtHead(int val) {
MyLinkedListNode newNode = new MyLinkedListNode(val, this.head);
this.head = newNode;
if (this.tail == null) {
this.tail = newNode;
}
this.sum++;
}
public void addAtTail(int val) {
MyLinkedListNode newNode = new MyLinkedListNode(val, null);
if (this.tail != null) {
this.tail.next = newNode;
}
this.tail = newNode;
if (this.head == null) {
this.head = newNode;
}
this.sum++;
}
public void addAtIndex(int index, int val) {
if (index > this.sum) return;
if (index == this.sum) {
addAtTail(val);
return;
}
MyLinkedListNode it = this.head;
for (int i = 0; i < index - 1; i++) {
it = it.next;
}
MyLinkedListNode newNode = new MyLinkedListNode(val, it.next);
it.next = newNode;
this.sum++;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= this.sum) return;
if (index == 0) {
this.head = this.head.next;
if (this.head == null) {
this.tail = null; // Empty list
}
this.sum--;
return;
}
MyLinkedListNode it = this.head;
for (int i = 0; i < index - 1; i++) {
it = it.next;
}
it.next = it.next.next;
if (it.next == null) {
this.tail = it; // Update tail if the last node is deleted
}
this.sum--;
}
}
206.反转链表
题目链接:力扣题目链接
文章讲解: 力扣题目链接
双指针法(常规,循环遍历)
代码:
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) return null;
if (head.next == null) return head;
ListNode cur = head;
ListNode prev = null;
ListNode temp = null;
while (cur != null) {
temp = cur.next;
cur.next = prev;
prev = cur;
cur = temp;
}
return prev;
}
}
递归法(妙但抽象)
代码:
class Solution {
ListNode reverseList(ListNode head) {
// 边缘条件判断
if(head == null) return null;
if (head.next == null) return head;
// 递归调用,翻转第二个节点开始往后的链表
ListNode last = reverseList(head.next);
// 翻转头节点与第二个节点的指向
head.next.next = head;
// 此时的 head 节点为尾节点,next 需要指向 NULL
head.next = null;
return last;
}
}