整个链表=头结点+后面整个链表
1 class Solution4 { 2 3 public ListNode removeElements(ListNode head, int val) { 4 5 if(head == null) //头结点为空,也就是整个链表为空, 6 return head; //对于一个空链表,要删除值为val的节点,结果还是空 7 8 ListNode res = removeElements(head.next, val); 9 //考虑头结点 10 if(head.val == val) 11 return res;//删除head,res存的就是head后面的节点 12 else{ //head不要删除, 13 head.next = res; //head后面的子链表删除val的得到的子链表衔接到head后 14 return head; 15 } 16 } 17 18 public static void main(String[] args) { 19 20 int[] nums = {1, 2, 6, 3, 4, 5, 6}; //声明一个数组是int[]类型的 21 ListNode head = new ListNode(nums);//调用ListNode方法,这里的head实际上是一个链表,由于构造函数public ListNode(int[] arr) 22 System.out.println(head);//这里的head虽然是一个头节点,但是根据我们在ListNode中覆盖的toString()方法,将打印以head为头节点的整个链表对应的字符串 23 24 ListNode res = (new Solution4()).removeElements(head, 6); 25 System.out.println(res); 26 } 27 }
1 public class ListNode { 2 3 public int val; 4 public ListNode next; 5 6 public ListNode(int x) { 7 val = x; 8 } 9 10 // 链表节点的构造函数 11 // 使用arr为参数,创建一个链表,当前的ListNode为链表头结点 12 public ListNode(int[] arr){ 13 14 if(arr == null || arr.length == 0) 15 throw new IllegalArgumentException("arr can not be empty"); 16 17 this.val = arr[0]; // this.val对应arr中索引为0的元素 18 //遍历整个数组,在这个过程中,我们一个一个的将数组中的每一个元素创建成新的ListNode,接在前一个节点上 19 ListNode cur = this; 20 for(int i = 1 ; i < arr.length ; i ++){ 21 cur.next = new ListNode(arr[i]); 22 cur = cur.next; //最后我们的这个this其实是:用for循环创建出来的链表相对应的头节点 23 } 24 } 25 26 // 以当前节点为头结点的链表信息字符串 27 @Override 28 public String toString(){ 29 30 StringBuilder s = new StringBuilder(); 31 ListNode cur = this; //cur为链表,包含多个节点 32 while(cur != null){ 33 s.append(cur.val + "->"); //cur.val被轮询到的某个链表节点的值 34 cur = cur.next; 35 } 36 s.append("NULL"); 37 return s.toString(); 38 } 39 }