day6
[0203.移除链表元素]
/**
* 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 dummy = new ListNode (-1, head);
ListNode cur = dummy.next;
while (cur != null){
if (cur.val == val){
cur.next = cur.next.next;
cur = cur.next;
}
cur = cur.next;
}
return dummy.next;
}
}
- java.lang.NullPointerException: Cannot read field "next" because "
.next" is null,不能读cur.next.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 dummy = new ListNode (-1, head);
ListNode cur = dummy.next;
ListNode pre = dummy;
while (cur != null){
if (cur.val == val){
pre.next = cur.next;
cur = cur.next;
}
else{
pre = cur;
cur = cur.next;
}
}
return dummy.next;
}
}
- 完成!记得之前本科学数据结构,课上老师经常只讲删除一个元素,而且都是伪代码,课程作业是否写过这种循环删除的印象不深了,所以我对原理的理解没啥大问题,但实际操作有些少,还需要多练练~
本文来自博客园,作者:跬步瑶,转载请注明原文链接:https://www.cnblogs.com/deservee/p/16849284.html

浙公网安备 33010602011771号