【11】Delete a node in the middle of a single linked list

来源:互联网 发布:学历网络教育报考时间 编辑:程序博客网 时间:2024/04/30 02:47

Question: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->

package CareerCup;public class DeleteMidNode {public DeleteMidNode(){}public boolean delete(Node node){if(node == null || node.next==null) return false;Node next = node.next;node.data = next.data;node.next = next.next;return true;}public static void main(String[] args){int[] data = new int[]{1,2,3,4,5};LinkedList ll = new LinkedList();for(int i=0;i<data.length;i++)ll.add(data[i]);System.out.println("The linkedlist:");ll.print();DeleteMidNode dmn = new DeleteMidNode();int n = 2;Node node = ll.getNode(n);dmn.delete(node);System.out.println("After delete the "+n+"th node,linkedlist now is:");ll.print();}}

Result: nothing is returned, but the new linked list looks like a->b->d->e