|
《Windows游戏编程大师技巧》(第二版)第11章(4) new_node->next = NULL; // good practice // step 2: what is the current state of the linked list? if (head==NULL) // case 1 { // empty list, simplest case head = tail = new_node; // return new node return(new_node); } // end if else if ((head != NULL) && (head==tail)) // case 2 { // there is exactly one element, just a little // finesse... head->next = new_node; tail = new_node; // return new node return(new_node); } // end if else // case 3 { // there are 2 or more elements in list // simply move to end of the list and add // the new node tail->next = new_node; tail = new_node; // return the new node return(new_node); } // end else } // end Insert_Node As you can see, the code is rather simple. But it's easy to mess up because you're dealing with pointers, so be careful! Also, the astute programmer will very quickly realize that with a little thought, cases two and three can be combined, but the code here is easier to follow. Now let's remove a node. 你可能觉得代码比较简单。但实际上它却很容易造成混乱,因为你处理的是指针,所以要小心谨慎!聪明的程序员脑筋一转便会很快地意识到case 2和case 3可以合二为一,但这里的代码易读性更好。下面我们来看一看节点的删除。 删除节点 删除节点比插入节点复杂,因为指针和内存都要重新定位和分配。大多数情况下,只需删除指定的一个节点。但这个节点的位置可能是头部、尾部或中间,因此你必须编写一个通用的算法来处理所有可能的情况。如果你没有将所有的情况都考虑进去并进行测试,那后果将是非常糟糕的! 一般而言,这个算法必须能够按所给定的关键字搜索链表、删除节点并释放其占用的内存。此外,该算法还必须能够修复指向该被删除节点的指针和该节点所指向的下一个节点的指针。看一看图11-3便会一目了然。 图11-3:从链表中删除节点 下面这段代码可以基于关键字ID,完成删除任意节点的操作: // again this function will modify the globals // head and tail (possibly) int Delete_Node(int id) // node to delete { // this function deletes a node from // the linked list given its id
|