-
-
Notifications
You must be signed in to change notification settings - Fork 315
/
DeleteMiddleNode.java
65 lines (56 loc) · 1.77 KB
/
DeleteMiddleNode.java
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
package com.ctci.linkedlists;
/**
* @author rampatra
* @since 2019-01-27
*/
public class DeleteMiddleNode {
/**
* Implement an algorithm to delete a node in the middle (i.e., any node but the first and last node, not
* necessarily the exact middle) of a singly linked list, given only access to that node.
* <p>
* EXAMPLE
* Input: the node c from the linked list a->b->c->d->e->f
* Result: nothing is returned, but the new linked list looks like a->b->d->e->f
*
* @param middle the node to be deleted
*/
private static void deleteMiddleNode(Node middle) {
if (middle == null || middle.next == null) {
return;
}
// copy the data from the next node over to the middle node, and then to delete the next node
Node next = middle.next;
middle.val = next.val;
middle.next = next.next;
}
public static void main(String[] args) {
Node l1 = new Node(1);
l1.next = new Node(2);
l1.next.next = new Node(3);
l1.next.next.next = new Node(4);
l1.next.next.next.next = new Node(5);
l1.next.next.next.next.next = new Node(6);
l1.print();
deleteMiddleNode(l1.next.next);
l1.print();
System.out.println("----");
l1 = new Node(1);
l1.next = new Node(2);
l1.next.next = new Node(3);
l1.print();
deleteMiddleNode(l1.next);
l1.print();
System.out.println("----");
l1 = new Node(1);
l1.next = new Node(3);
l1.print();
deleteMiddleNode(l1);
l1.print();
System.out.println("----");
l1 = new Node(1);
l1.next = new Node(3);
l1.print();
deleteMiddleNode(l1.next);
l1.print();
}
}