203.移除链表元素
题目链接:https://leetcode.cn/problems/remove-linked-list-elements/
思路
遍历一遍链表,把不需要删除的节点摘出来即可。时间O(n),空间O(1)
代码
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return null;
}
ListNode dummy = new ListNode(-1, head);
ListNode tail = dummy, cur = head;
while (cur != null) {
if (cur.val != val) {
tail.next = cur;
tail = cur;
}
cur = cur.next;
}
tail.next = null;
return dummy.next;
}
}
707.设计链表
题目链接:https://leetcode.cn/problems/design-linked-list/
思路
看似简单,细节特别多,花了很长的时间(打死也不想做第二遍)
代码
class MyLinkedList {
private ListNode head;//头结点
private ListNode tail;//尾结点
private int len;//记录链表长度
public MyLinkedList() {
}
public int get(int index) {
if (len <= index) {
return -1;
}
ListNode p = head;
for (int i = 0; i < index; i++) {
p = p.next;
}
return p.val;
}
public void addAtHead(int val) {
ListNode newHead = new ListNode(val);
if (head == null) {
//只要head和tail一个为null,则该链表没有节点
tail = newHead;
} else {
newHead.next = head;
}
head = newHead;
len++;
}
public void addAtTail(int val) {
ListNode newTail = new ListNode(val);
if (tail == null) {
head = newTail;
} else {
tail.next = newTail;
}
tail = newTail;
len++;
}
public void addAtIndex(int index, int val) {
if (len == index) {
addAtTail(val);
} else if (index <= 0) {
addAtHead(val);
} else if (index < len) {
ListNode p = head;
//找到待插入节点的前一个节点
for (int i = 0; i < index - 1; i++) {
p = p.next;
}
p.next = new ListNode(val, p.next);
len++;
}
}
public void deleteAtIndex(int index) {
if (len < index + 1 || index < 0) {
return;
}
if (len == 1) {
//节点个数=1,index只能=0
tail = null;
head = null;
len--;
return;
}
//此时节点个数>1
if (index == 0) {
//删除头结点
head = head.next;
len--;
return;
}
ListNode p = head;
//找到待删除节点的前一个节点
for (int i = 0; i < index - 1; i++) {
p = p.next;
}
p.next = p.next.next;
if (p.next == null) {
//刚才删除的是尾节点
tail = p;
}
len--;
}
}
206.反转链表
题目链接:https://leetcode.cn/problems/reverse-linked-list/
思路
- 头插法。时间O(n),空间O(1)
- 递归。时间O(n),空间O(n)
代码
//头插法
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
//节点个数<=1
return head;
}
ListNode dummy = new ListNode(-1);
ListNode next = head;
while (head != null) {
next = head.next;
head.next = dummy.next;
dummy.next = head;
head = next;
}
return dummy.next;
}
}
//递归
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
}