0 课程地址
https://coding.imooc.com/lesson/207.html#mid=13434
1 重点关注
1.1 leetCode的代码 如何本地调试
详见3.1
1.2 遗忘的点
链表增加元素时,是根据前一个节点判断的
2 课程内容
3 Coding
3.1 leetCode的代码(上节的502问题) 如何本地调试
- 链表类本地:
package com.company; 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; } /** * 传入数组的有参构造函数 增加,是用前一个元素去增 不要用当前元素,重点 * @author weidoudou * @date 2022/11/1 7:08 * @param vals 请添加参数描述 * @return null **/ public ListNode(int[] vals){ if(vals.length==0||vals==null){ throw new IllegalArgumentException("传入的数组不能为空"); } this.val = vals[0]; ListNode pre = this; for(int i = 1;i<vals.length;i++){ pre.next = new ListNode(vals[i]); pre = pre.next; } } @Override public String toString() { final StringBuffer sb = new StringBuffer(""); ListNode cur = this; while (cur!=null){ sb.append(cur.val).append("->"); cur = cur.next; } sb.append("Null"); return sb.toString(); } }
- 测试类:
package com.company; /** * 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 dummyHead = new ListNode(); dummyHead.next = head; ListNode preNode = dummyHead; //1? 判断非空 while(preNode.next!=null){ if(preNode.next.val==val){ ListNode delNode = preNode.next; preNode.next = delNode.next; delNode.next = null; }else{ preNode = preNode.next; } } return dummyHead.next; } public static void main(String[] args) { int[] nums = {1,2,6,3,4,5,6}; ListNode listNode = new ListNode(nums); System.out.println(listNode); ListNode res = new Solution().removeElements(listNode,6); System.out.println(res); } }
- 测试结果:
1->2->6->3->4->5->6->Null 1->2->3->4->5->Null Process finished with exit code 0
标签:ListNode,val,int,next,链表,public,数据结构,preNode,Leetcode From: https://www.cnblogs.com/1446358788-qq/p/16846497.html