203、删除链表节点
链表题,无论如何先造dummy
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummyNode = new ListNode();
dummyNode.next = head;
ListNode preNode = dummyNode;
while(head != null) {
if (head.val == val) {
preNode.next = head.next;
} else {
preNode = preNode.next;
}
head = head.next;
}
return dummyNode.next;
}
}
代码优化
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummyNode = new ListNode();
dummyNode.next = head;
ListNode cur = dummyNode;
while(cur.next != null) {
// 如果下一个值是要删除的,那么只需要将当前的下一个指向下一个的下一个
if (head.val == val) {
cur.next = cur.next.next;
} else {
// 正常往后移一位
cur = cur.next;
}
}
return dummyNode.next;
}
}
206 反转链表
理解递归
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode last = reverseList(head.next);
head.next.next = head;
head.next = null;
return last;
}
}