Technology Sharing

JAVA Learning - Practice using Java to implement "removing linked list elements"

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

question:

Given a linked list head node head and an integer val, delete all nodes in the linked list that satisfy Node.val == val and return the new head node.

Example 1:

Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]
Example 2:

Input: head = [], val = 1
Output: []
Example 3:

Input: head = [7,7,7,7], val = 7
Output: []
hint:

The number of nodes in the list is in the range [0, 104]
1 <= Node.val <= 50
0 <= val <= 50

Solution ideas:

The following is the code to solve the problem of removing elements from a linked list using Java:

  1. class ListNode {
  2. int val;
  3. ListNode next;
  4. ListNode(int val) {
  5. this.val = val;
  6. }
  7. }
  8. public class RemoveLinkedListElements {
  9. public ListNode removeElements(ListNode head, int val) {
  10. // 创建一个虚拟头节点,方便处理头节点可能被删除的情况
  11. ListNode dummy = new ListNode(0);
  12. dummy.next = head;
  13. ListNode curr = dummy;
  14. while (curr.next!= null) {
  15. if (curr.next.val == val) {
  16. curr.next = curr.next.next;
  17. } else {
  18. curr = curr.next;
  19. }
  20. }
  21. return dummy.next;
  22. }
  23. public static void main(String[] args) {
  24. // 构建链表
  25. ListNode head = new ListNode(1);
  26. ListNode node2 = new ListNode(2);
  27. ListNode node3 = new ListNode(6);
  28. ListNode node4 = new ListNode(3);
  29. ListNode node5 = new ListNode(4);
  30. ListNode node6 = new ListNode(5);
  31. ListNode node7 = new ListNode(6);
  32. head.next = node2;
  33. node2.next = node3;
  34. node3.next = node4;
  35. node4.next = node5;
  36. node5.next = node6;
  37. node6.next = node7;
  38. RemoveLinkedListElements solution = new RemoveLinkedListElements();
  39. ListNode newHead = solution.removeElements(head, 6);
  40. // 打印移除指定值后的链表
  41. while (newHead!= null) {
  42. System.out.print(newHead.val + " ");
  43. newHead = newHead.next;
  44. }
  45. }
  46. }

The idea of ​​this code is to create a virtual head node 'dummy', and point its 'next' pointer to the head node 'head' of the original linked list. Then, through a loop, traverse the linked list, and when a node with a value equal to 'val' is encountered, it is deleted from the linked list. Finally, the 'next' node of 'dummy' is returned, which is the head node of the new linked list after deleting the node with the specified value.
(The article is a summary and reference of the author's personal experience in learning Java. If there are any inappropriate or wrong places, please criticize and correct them. I will definitely try my best to correct them. If there is any infringement, please contact the author to delete the post.)