1. 203移除链表元素
answer:
思路:
dummy.next = head; // 返回用的
考虑p head;
<1> 如果 head.val = val;
p.next = head.next;
head = head.next;
<2>不等则顺移
p = p.next;
head = head.next;
public ListNode removeElements(ListNode head, int val) {
if (head == null)
return null;
ListNode dummy = new ListNode();
dummy.next = head;
ListNode p = dummy;
while (head != null) {
if (head.val == val) {
p.next = head.next;
head = head.next;
} else {
p = p.next;
head = head.next;
}
}
return dummy.next;
}
2. 206 反转链表
answer:
此题递归法不会!后面看下!。;
p = null;
考虑p, head;
head.next = p;
再顺移:
p = head;
head = q;(此处q得先保存:ListNode q = head.next;)
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode p = null;
while (head != null) {
ListNode q = head.next;
head.next = p;
p = head;
head = q;
}
return p;
}
NOTE:
<1> null.next; 执行时会出错;
<2>
ListNode p;
p.next = head;出错,没有分配空间直接用了;
<3>
ListNode p;
p = head.next;对的!正常使用。。