|
| 1 | +package linked_list; |
| 2 | + |
| 3 | +public class LinkedListProcessor { |
| 4 | + |
| 5 | + static class ListNode { |
| 6 | + int val; |
| 7 | + ListNode next; |
| 8 | + |
| 9 | + ListNode(int val) { |
| 10 | + this.val = val; |
| 11 | + } |
| 12 | + } |
| 13 | + |
| 14 | + public ListNode deleteMiddle(ListNode head) { |
| 15 | + if (head == null || head.next == null) return null; |
| 16 | + |
| 17 | + ListNode fast = head, slow = head, prev = null; |
| 18 | + |
| 19 | + while (fast != null && fast.next != null) { |
| 20 | + fast = fast.next.next; |
| 21 | + prev = slow; |
| 22 | + slow = slow.next; |
| 23 | + } |
| 24 | + |
| 25 | + prev.next = slow.next; |
| 26 | + |
| 27 | + return head; |
| 28 | + } |
| 29 | + |
| 30 | + private static ListNode arrayToList(int[] arr) { |
| 31 | + ListNode dummy = new ListNode(0); |
| 32 | + ListNode tail = dummy; |
| 33 | + for (int num : arr) { |
| 34 | + tail.next = new ListNode(num); |
| 35 | + tail = tail.next; |
| 36 | + } |
| 37 | + return dummy.next; |
| 38 | + } |
| 39 | + |
| 40 | + private static boolean areListsEqual(ListNode l1, ListNode l2) { |
| 41 | + while (l1 != null && l2 != null) { |
| 42 | + if (l1.val != l2.val) return false; |
| 43 | + l1 = l1.next; |
| 44 | + l2 = l2.next; |
| 45 | + } |
| 46 | + return l1 == null && l2 == null; |
| 47 | + } |
| 48 | + |
| 49 | + public static void main(String[] args) { |
| 50 | + LinkedListProcessor processor = new LinkedListProcessor(); |
| 51 | + |
| 52 | + ListNode head1 = arrayToList(new int[]{1,3,4,7,1,2,6}); |
| 53 | + ListNode expected1 = arrayToList(new int[]{1,3,4,1,2,6}); |
| 54 | + assert areListsEqual(processor.deleteMiddle(head1), expected1) : "Test case 1 failed"; |
| 55 | + |
| 56 | + ListNode head2 = arrayToList(new int[]{1,2,3,4}); |
| 57 | + ListNode expected2 = arrayToList(new int[]{1,2,4}); |
| 58 | + assert areListsEqual(processor.deleteMiddle(head2), expected2) : "Test case 2 failed"; |
| 59 | + |
| 60 | + ListNode head3 = arrayToList(new int[]{2,1}); |
| 61 | + ListNode expected3 = arrayToList(new int[]{2}); |
| 62 | + assert areListsEqual(processor.deleteMiddle(head3), expected3) : "Test case 3 failed"; |
| 63 | + |
| 64 | + System.out.println("All test cases passed!"); |
| 65 | + } |
| 66 | +} |
0 commit comments