LeetCode 203.移除链表元素
题目链接:https://leetcode.cn/problems/remove-linked-list-elements/description/
文章链接:https://programmercarl.com/%E9%93%BE%E8%A1%A8%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80.html
思路
设置虚拟头节点。
时间复杂度o(n),空间复杂度o(1)。
public ListNode removeElements(ListNode head, int val) {
ListNode p;
if (head == null)
return null;
ListNode L = new ListNode(-1, head);
p = L;
while (p.next != null) {
if (p.next.val == val){
p.next = p.next.next;
}else {
p = p.next;
}
}
return L.next;
}
LeetCode 206.反转链表
题目链接:https://leetcode.cn/problems/reverse-linked-list/description/文章讲解:https://programmercarl.com/0209.%E9%95%BF%E5%BA%A6%E6%9C%80%E5%B0%8F%E7%9A%84%E5%AD%90%E6%95%B0%E7%BB%84.html
思路
使用三个指针,直接反转链表即可
时间复杂度o(n),空间复杂度o(1)。
public ListNode reverseList(ListNode head) {
if (head == null)
return null;
ListNode p, pre, r;
ListNode L = new ListNode(-1, head);
p = L.next;
r = p.next;
p.next = null;
while (r != null){
pre = p;
p = r;
r = r.next;
p.next = pre;
}
return p;
}