原文:
Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node.
EXAMPLE
Input: the node ‘c’ from the linked list a->b->c->d->e Result: nothing is returned, but the new linked list looks like a->b->d->e
译文:
实现一个算法来删除单链表中间的一个结点,只给出指向那个结点的指针。
例子:
输入:指向链表a->b->c->d->e中结点c的指针
结果:不需要返回什么,得到一个新链表:a->b->d->e
只给出中间节点的地址,可以将mid.next的data给mid,然后删除mid.next。
public static boolean delMidNode(LinkedListNode mid) {
if (mid == null || mid.next == null) {
return false;
}
LinkedListNode midNext = mid.next;
mid.data = midNext.data;
mid.next = midNext.next;
return true;
}
testcase
public static void main(String args[]) {
LinkedListNode head = null;
LinkedListNode tmp = null;
int a[] = {1, 2, 1};
for (int i = 0; i < a.length; i++) {
LinkedListNode next = new LinkedListNode(a[i]);
if (i == 0) {
head = tmp = next;
continue;
}
tmp.next = next;
tmp = next;
}
// Print the list(before)
tmp = head;
while (tmp != null) {
System.out.println(tmp.data);
tmp = tmp.next;
};
LinkedListNode mid = head.next;
delMidNode(mid); // Print the list(before)
while (head != null) {
System.out.println(head.data);
head = head.next;
};
}