Implement an algorithm to delete a node in the middle of a singly 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:
就是,从后向前,一个个地copy,似乎没有别的办法了。
public static Node getMiddle(LinkList list, int listSize){
Node tmp = list.head;
for(int i = 0 ;i<(int)(listSize/2); i++){
tmp = tmp.next;
}
return tmp;
}
public static void deleteMiddleNode(Node node){
Node nextNode = node.next;
while(nextNode.next != null){
node.data = nextNode.data;
node = nextNode;
nextNode = nextNode.next;
}
node.data= nextNode.data;
node.next=null;
}
记得,检查边界值。
No comments:
Post a Comment