我想通过升序将元素添加到我的链表顺序,但我的代码只是正确地保持列表的最小节点。我的函数接受参数作为数据。有人知道是我的错吗?
while(Node->nextPtr!=NULL && capture!=1) {
if(Node->nextPtr->data > data){
capture = 1;
Node->nextPtr = Temp;
Temp->nextPtr = nextNode;
}
else {
Node = Node->nextPtr;
nextNode = Node->nextPtr;
}
}
为什么不在以下几行:
while(Node->data < data && Node->nextPtr!=NULL) Node = node->nextPtr;
Temp->nextPtr = Node->nextPtr;
Node->nextPtr = Temp;
似乎更清晰,并且您不需要跟踪捕获和nextPtr。
(我为任何小错误道歉,这里有点晚了:p)
欢呼
//Bubble Sort to sort the elements
void sort(){
struct Stack *prev,*curr;
int temp;
curr=prev=top;
curr=curr->next;
while(curr!=NULL){
prev=top;
while(prev!=curr->next){
if(prev->info<curr->info){
temp = curr->info;
curr->info=prev->info;
prev->info = temp;
}
prev=prev->next;
}
curr=curr->next;
}
}
好吧,你的示例代码很奇怪,我已经有一段时间没有在C语言中使用链表了,但是你可以:
listNode * insertNode(* listNode newNode){
// throw away variable 32 or 64 bits on the stack, either way no worries since
// it will poof after the call.
currNode * listNode ;
// assume list head is a global since it normally would be
currNode = ListHead ;
// start from the list head and move through until you hit the end
// if you have not inserted before the end, tack it onto the end
// this will traverse until you hit the tail or data is greater
while(currNode->next and (newNode->data > currNode->data) ) ;
// insert the new node after current node and there is a next node
if (currNode->next) {
newNode->next = currNode->next ;
newNode->*next->prev = newNode ;
currNode->next = newNode ;
newNode->prev = currNode ;
}
else
{
// we hit the end of the list on traversal so just tack it onto the end.
currNode->next = newNode ;
newNode->prev = currNode ;
newNode-> next = null ;
}
// and finally return the node in its proper position.
return newNode ;
}
现在这个函数不知道"data"是什么类型,这很好,但通常它是在某个地方键入的,或者数据是指针类型,你可以将指针size_t位推入以获得实际值。我想我是对的。