链表结构
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;
}
}
添加虚拟头节点
看到删除的题目,考虑虚拟头节点
添加虚拟节点后,删除操作可以统一
public ListNode removeElements(ListNode head, int val) {
if (head == null) return null;
ListNode dummy = new ListNode(-1, head);
ListNode pre = dummy;
ListNode cur = head;
while (cur != null) {
if (cur.val == val) {
pre.next = cur.next;
}
//不相等,则移动pre指针
else {
pre = cur;
}
cur = cur.next;
}
return dummy.next;
}public ListNode removeElements(ListNode head, int val) {
if
}
设计链表
707. 设计链表
反转链表
双指针
public ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode pre = null;
while (cur != null) {
ListNode tmp = cur;
cur = cur.next;
tmp.next = pre;
pre = tmp;
}
return pre;
}