203.移除链表元素
思路:
有两种方法,有无虚拟头节点
删除时注意删除的是cur.next,因此判断的是cur.next != null
class Solution { //有虚拟头结点
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(-1, head);
ListNode cur = dummy;
while (cur != null && cur.next != null) {
if (cur.next.val == val) cur.next = cur.next.next;
else cur = cur.next;
}
return dummy.next;
}
}
class Solution { //无虚拟头结点
public ListNode removeElements(ListNode head, int val) {
while (head != null && head.val == val) head = head.next;
ListNode cur = head;
while (cur != null && cur.next != null) {
if (cur.next.val == val) {
cur.next = cur.next.next;
} else cur = cur.next;
}
return head;
}
}
707.设计链表
这一题是链表的综合应用,思路上来说并不难,但是每个函数的边界值判断条件都要非常注意
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
}
class MyLinkedList {
int size;
ListNode head;
public MyLinkedList() {
size = 0;
head = new ListNode(0);
}
public int get(int index) {
if (index < 0 || index > size - 1) return -1;
ListNode cur = head.next;
while (index-- > 0) {
cur = cur.next;
}
return cur.val;
}
public void addAtHead(int val) {
ListNode newNode = new ListNode(val);
newNode.next = head.next;
head.next = newNode;
size++;
}
public void addAtTail(int val) {
ListNode newNode = new ListNode(val);
ListNode cur = head;
while (cur.next != null) {
cur = cur.next;
}
cur.next = newNode;
size++;
}
public void addAtIndex(int index, int val) {
if (index < 0 || index > size) return;
ListNode newNode = new ListNode(val);
ListNode cur = head;
while (index-- > 0) {
cur = cur.next;
}
newNode.next = cur.next;
cur.next = newNode;
size++;
}
public void deleteAtIndex(int index) {
if (index < 0 || index > size - 1) return;
ListNode cur = head;
while (index-- > 0) {
cur = cur.next;
}
cur.next = cur.next.next;
size--;
}
}
206.反转链表
有两种做法
第一种双指针,定义pre和cur,分别指向前一个node和当前node
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode pre = null;
while (cur != null) {
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}
第二种递归
class Solution {
static ListNode reverse(ListNode cur, ListNode pre) {
if (cur == null) return pre;
ListNode tmp = cur.next;
cur.next = pre;
return reverse(tmp, cur);
}
public ListNode reverseList(ListNode head) {
return reverse(head, null);
}
}