【发布时间】:2011-05-08 22:01:12
【问题描述】:
我想知道这个函数是如何在尝试从单链表中删除节点时获取根节点的。我了解整个删除部分。
class LinkedList {
LinkedListNode root;
// Remove the nodes which contain data equal to obj
void deleteNode(Object obj) {
// special case for root
if( root.data.equals(obj) ) {
root = root.next;
}
LinkedListNode current = root;
// iterate through list looking for obj
while( current.next != null ) {
// match found
if( current.next.data.equals(obj) ) {
// cut out the node
current.next = current.next.next;
}
current = current.next;
}
}
}
private class LinkedListNode {
Object data;
LinkedListNode next;
}
我不知道为什么仅仅通过创建一个 LinkedListNode 根,它指的是根节点。清晰易懂的帮助将不胜感激。
Ff理论上我没有创建LinkedListNode根,我可以给delete函数传入一个额外的参数,然后根据它的数据指定哪个是head吗?
LinkedListNode deleteNode(LinkedListNode head, int d) {
LinkedListNode n = head;
if (n.data == d) {
return head.next; /* moved head */
}
while (n.next != null) {
if (n.next.data == d) {
n.next = n.next.next;
return head; /* head didn’t change */
}
n = n.next;
}
}
【问题讨论】:
标签: c# linked-list root