-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathRemoveMidNode.java
64 lines (52 loc) · 1.22 KB
/
RemoveMidNode.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
package com.demo;
/**
* 删除单向链表中间节点
* @author kexun
*
*/
public class RemoveMidNode {
public static void main(String[] args) {
System.out.println(Math.ceil((double)(5*7)/(double)6));
Node n1 = new RemoveMidNode().new Node(1);
Node n2 = new RemoveMidNode().new Node(2);
Node n3 = new RemoveMidNode().new Node(3);
Node n4 = new RemoveMidNode().new Node(4);
Node n5 = new RemoveMidNode().new Node(5);
Node n6 = new RemoveMidNode().new Node(6);
Node n7 = new RemoveMidNode().new Node(7);
Node n8 = new RemoveMidNode().new Node(8);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = n6;
n6.next = n7;
n7.next = n8;
RemoveMidNode r = new RemoveMidNode();
Node h = r.removeMidNode(n1);
while (h != null) {
System.out.println(h.data);
h = h.next;
}
}
public Node removeMidNode(Node head) {
if (head == null || head.next == null) {
return null;
}
Node pre = head;
Node cur = head.next.next;
while (cur.next != null && cur.next.next != null) {
pre = pre.next;
cur = cur.next.next;
}
pre.next = pre.next.next;
return head;
}
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
}