LeetCode 203:根据值删除节点
题目:
方式一:
方法二:
代码示例:
package com.zy.leetcode.LeetCode_203;
/**
* @Author: zy
* @Date: 2024-12-25-11:49
* @Description:
* 根据值删除节点
*/
public class ListNode_203 {
int val;
ListNode_203 next;
ListNode_203(int val) {
this.val = val;
this.next = null;
}
public ListNode_203(int val, ListNode_203 next) {
this.val = val;
this.next = next;
}
public ListNode_203() {
}
public ListNode_203 removeVal(ListNode_203 o1, int target) {
ListNode_203 s = new ListNode_203(-1, o1);
ListNode_203 p1 = s;
ListNode_203 p2 = s.next;
while (p2 != null) {
if (p2.val == target) {
//删除,p2向后平移
p1.next = p2.next;
} else {
p1 = p1.next;
}
p2 = p2.next;
}
//返回头节点,不返回
return s.next;
}
public ListNode_203 removeValChange(ListNode_203 o1, int target) {
ListNode_203 s = new ListNode_203(-1, o1);
ListNode_203 p1 = s;
ListNode_203 p2;
while ((p2 = p1.next) != null) {
if (p2.val == target) {
//删除,p2向后平移
p1.next = p2.next;
} else {
p1 = p1.next;
}
//p2 = p2.next;
}
//返回头节点,不返回
return s.next;
}
/**
* 递归
* @param o1
* @param target
* @return
*/
public ListNode_203 removeVal2(ListNode_203 o1, int target) {
if (o1 == null) {
return null;
}
if (o1.val == target) {
//如果相等,则返回后续节点递归结果
return removeVal2(o1.next, target);
} else {
//如果不相等,则返回后续节点,并更新当前节点所指向的下一节点
o1.next = removeVal2(o1.next, target);
return o1;
}
}
// Helper method to print the linked list
private static void printLinkedList(ListNode_203 head) {
ListNode_203 current = head;
while (current != null) {
System.out.print(current.val + " ");
current = current.next;
}
System.out.println(); // For a new line after printing the list
}
// Helper method to create a linked list from an array of values
private static ListNode_203 createLinkedList(int[] values) {
if (values.length == 0) {
return null;
}
ListNode_203 head = new ListNode_203(values[0]);
ListNode_203 current = head;
for (int i = 1; i < values.length; i++) {
current.next = new ListNode_203(values[i]);
current = current.next;
}
return head;
}
public static void main(String[] args) {
int[] values1 = {2, 2, 3, 4, 2, 5, 6};
int[] values2 = {1, 2, 6, 3, 6};
int[] values3 = {7, 7, 7, 7, 7};
ListNode_203 head1 = createLinkedList(values1);
printLinkedList(head1);
ListNode_203 head2 = createLinkedList(values2);
printLinkedList(head2);
ListNode_203 head3 = createLinkedList(values3);
printLinkedList(head3);
System.out.println("\n-------------");
ListNode_203 listNode1 = new ListNode_203().removeVal(head1, 2);
ListNode_203 listNode12 = new ListNode_203().removeValChange(head1, 2);
ListNode_203 listNode13 = new ListNode_203().removeVal2(head1, 2);
printLinkedList(listNode1);
printLinkedList(listNode12);
printLinkedList(listNode13);
System.out.println("\n-------------");
ListNode_203 listNode2 = new ListNode_203().removeVal(head2, 6);
printLinkedList(listNode2);
System.out.println("\n-------------");
ListNode_203 listNode3 = new ListNode_203().removeVal(head3, 7);
printLinkedList(listNode3);
}
}