您的位置:首页 > Web前端 > Node.js

[CrackCode] 2.3 Delete a node in the middle of a single linked list

2014-01-27 01:44 435 查看
Implement an algorithm to delete a node in the middle of a single linked list, givenonly 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

=================

Analysis:

We can do nothing to delete the target as we do not have the target node's previous node. However, we can copy all the attribute of the node after the target node (say "next node") to target node, then delete the "next node". Result of which is similar
to deleting the current node.

Node that if target node is the last node of the linked list, this approach would not work.

public class Answer {
public static void solution(LinkedListNode target){
if(target == null || target.next == null) return;

LinkedListNode next = target.next;
target.data = next.data;
target.next = next.next;
return;
}

public static void main(String[] args) {
LinkedListNode head = AssortedMethods.randomLinkedList(10, 0, 10);
System.out.println(head.printForward());
solution(head.next.next.next); // delete node 4
System.out.println(head.printForward());
}
}


Note: Please download the crackcode library before running the program.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: