|
《Windows游戏编程大师技巧》(第二版)第11章(3) 下面是源代码: void Traverse_List(NODE_PTR head) { // this function traverses the linked list and prints out // each node // test if head is null if (head==NULL) { printf("\nLinked List is empty!"); return; } // end if // traverse while nodes while (head!=NULL) { // visit the node, print it out, or whatever... printf("\nNode Data: id=%d", head->id); printf("\nage=%d,head->age); printf("\nname=%s\n",head->name); // advance to next node (simple!) head = head->next; } // end while print("\n"); } // end Traverse_List 很酷是不是?下一步,让我们看一看如何在链表中插入一个节点。 插入节点 插入节点的第一步是创建该节点。创建节点有两种方法:你可以将新的数据元素传递给插入函数,由该函数来构造一个新节点;或者先构造一个新节点,然后将它传递给插入函数。这两种方法在本质上是相同的。 此外,还有许多方法可以实现节点插入链表的操作。蛮横的做法是将要插入的节点插在链表的开头或结尾。如果你不关心链表中节点的顺序,这倒不失为一个便捷的方法。但如果想保持链表原来的排序,你就应当采用更聪明的插入算法,这样可以保证插入节点后的链表仍然保持升序或降序的顺序。这也可以让以后进行搜索时速度更快。 为简明起见,我举一个最简单的节点插入方法的例子,也就是将节点插在链表的末尾。其实按顺序的节点插入算法并不太复杂。首先要扫描整个链表,找出新节点所要插入的位置,然后将其插入。惟一的问题就是保证不要丢失任何指针和信息。 下面的源代码将一个新节点插入链表的尾部(比插入链表头部难度稍大)。注意一下特殊的情况,即空链表和只有一个元素的链表: // Access the global head and tail to make code easier // in real life, you might want to use ** pointers and // modify head and tail in the function ??? NODE_PTR Insert_Node(int id, int age, char *name) { // this function inserts a node at the end of the list NODE_PTR new_node = NULL; // step 1: create the new node new_node = (NODE_PTR)malloc(sizeof(NODE)); // in C++ use new operator // fill in fields new_node->id = id; new_node->age = age; strcpy(new_node->name,name); // memory must be copied!
|