用C语言对链表进行排序
我想通过升序向我的链表顺序添加元素,但我的代码只正确地保留了列表的最小节点。我的函数以参数作为数据。有人知道我的错吗用C语言对链表进行排序,c,linked-list,C,Linked List,我想通过升序向我的链表顺序添加元素,但我的代码只正确地保留了列表的最小节点。我的函数以参数作为数据。有人知道我的错吗 while(Node->nextPtr!=NULL && capture!=1) { if(Node->nextPtr->data > data){ capture = 1; Node->nextPtr = Temp; Temp->nextPtr = nextNode;
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;
while(Node->datanextPtr!=NULL)Node=Node->nextPtr;
Temp->nextPtr=Node->nextPtr;
节点->nextPtr=Temp;
看起来更清晰,您不需要跟踪捕获的和下一个TPTR
(我为任何小错误道歉,这里有点晚了:p)
干杯好的,您的示例代码很奇怪,我已经有一段时间没有用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”是什么类型,这很好,但通常它是在某个地方键入的,或者数据是指针类型的,您可以将指针大小按位以获取实际值。嗯,我想我是对的。//气泡排序对元素进行排序
//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;
}
}
空排序(){
结构堆栈*prev,*curr;
内部温度;
当前=上一个=顶部;
当前=当前->下一步;
while(curr!=NULL){
prev=顶部;
while(上一个!=当前->下一个){
如果(上一个->信息){
温度=当前->信息;
当前->信息=当前->信息;
上一个->信息=温度;
}
上一个=上一个->下一个;
}
当前=当前->下一步;
}
}
代码示例看起来不完整,什么是Temp?…在满足条件后,您的中断在哪里?Temp是一个节点并保存数据。我的意思是像Temp->data=data;我在那里写的时候忘记了break。如果(Node->nextPtr->data>data){…capture=1..}和(Node->nextPtr!=NULL&&capture!=1)@justuser改为编辑你的帖子,我的break就可以了。