简体   繁体   English

在C中排序链接列表

[英]Sorting Linked List in C

I want to add elements to the my linked list order by ascending but my code just hold minimum node of the lists correctly. 我想通过升序将元素添加到我的链接列表顺序中,但是我的代码只正确保存了列表的最小节点。 My function take an argument as data. 我的函数将参数作为数据。 Anybody have any idea about my fault? 有人对我的错有任何想法吗?

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;
    }
}
//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;
    }

 }

why not something in the lines of: 为什么不符合以下内容:

while(Node->data < data && Node->nextPtr!=NULL) Node = node->nextPtr;
Temp->nextPtr = Node->nextPtr;
Node->nextPtr = Temp;

Seems clearer, and you don't need to keep track of captured and nextPtr. 似乎更清晰,您无需跟踪捕获的和nextPtr。

(I apologize for any small mistake, it's kinda late here :P) (对于任何小错误,我深表歉意,这里有点晚了:P)

Cheers 干杯

Ok, your sample code is weird and it has been a while since I did a linked list in C but here you go: 好的,您的示例代码很奇怪,自从我在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 ;

}

Now this function has no idea what type "data" is and that is fine, but typically it is typed someplace or the data is a pointer type and you can push a pointer size_t bits in to get the actual value. 现在,此函数不知道“数据”是什么类型,这很好,但是通常在某个地方键入它,或者数据是指针类型,您可以将指针的size_t位压入以获取实际值。 Meh I think I got it right. 嗯,我想我做对了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM