在C上的一個簡單鏈表實現中,我找不到一行名爲insert()的函數。 它需要一個字符並按字母順序添加到鏈接列表中。 該行是關於在列表爲空時創建新節點的。由於列表中只有一個節點,因此該行應該像我所評論的那樣,我錯了嗎?在鏈表中插入新節點
/****************************************************/
void insert(ListNodePtr *sPtr, char value){
ListNodePtr newPtr;
ListNodePtr previousPtr;
ListNodePtr currentPtr;
newPtr = malloc(sizeof(ListNode));
if(newPtr != NULL){ //is space available
newPtr->data = value; //place value in node
newPtr->nextPtr = NULL; //node does not link to another node
previousPtr = NULL;
currentPtr = *sPtr; //indirection to startPtr
while(currentPtr != NULL && value > currentPtr->data){
previousPtr = currentPtr; //walk to ...
currentPtr = currentPtr->nextPtr; //... next node
}
//insert new node at the beginning of the list
if(previousPtr == NULL){
newPtr->nextPtr = *sPtr; /////////////////////////////////////////////// newPtr->nextPtr = NULL ???
*sPtr = newPtr;
}
else{ //insert new node between previousPtr and currentPtr
previousPtr->nextPtr = newPtr;
newPtr->nextPtr = currentPtr;
}
}
else
printf("%c not inserted. No memory available.\n", value);
}//end-of insert
/*******************************************************/
main()中的typedef指令是;
typedef struct listNode ListNode;
typedef ListNode* ListNodePtr;
和函數insert()在main()中是這樣調用的;
insert(&startPtr, item);
main()中startPointer的初始化;
ListNodePtr startPtr = NULL;
啊,你編輯正確,因爲我張貼我的答案。接得好 – DTing 2011-03-07 01:16:53