-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeleteMiddleNode.java
More file actions
77 lines (62 loc) · 2 KB
/
Copy pathDeleteMiddleNode.java
File metadata and controls
77 lines (62 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package LeetcodePractice;
public class DeleteMiddleNode {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public static ListNode deleteMiddle(ListNode head) {
if (head == null || head.next == null) {
return null;
}
ListNode slow = head, fast = head, prev = null;
while (fast != null && fast.next != null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = slow.next;
return head;
}
public static void printList(ListNode head) {
ListNode current = head;
while (current != null) {
System.out.print(current.val);
if (current.next != null) System.out.print(" -> ");
current = current.next;
}
System.out.println();
}
public static ListNode createList(int[] values) {
ListNode dummy = new ListNode(0);
ListNode current = dummy;
for (int val : values) {
current.next = new ListNode(val);
current = current.next;
}
return dummy.next;
}
public static void main(String[] args) {
int[] input1 = {1, 3, 4, 7, 1, 2, 6};
ListNode head1 = createList(input1);
System.out.print("Original: ");
printList(head1);
head1 = deleteMiddle(head1);
System.out.print("After deletion: ");
printList(head1);
int[] input2 = {1, 2, 3, 4};
ListNode head2 = createList(input2);
System.out.print("\nOriginal: ");
printList(head2);
head2 = deleteMiddle(head2);
System.out.print("After deletion: ");
printList(head2);
int[] input3 = {2, 1};
ListNode head3 = createList(input3);
System.out.print("\nOriginal: ");
printList(head3);
head3 = deleteMiddle(head3);
System.out.print("After deletion: ");
printList(head3);
}
}