昨天笔试,遇到一个单向链表排序的问题,感觉挺简单的,后来发现还是做错了。
今天在机器上调了半天终于调试成功了。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdlib.h>
#include <assert.h
typedef struct _Node
{
struct _Node * next;
int value;
} Node;
////////////////////////////////////////
//只在单向链表的尾部插入节点
////////////////////////////////////////
void insert(Node ** root, int new_value)
{
Node * cur, * newnode;
while((cur = *root) != NULL)
root = &cur->next;
newnode = (Node *)malloc(sizeof(Node));
assert(NULL != newnode);
newnode->value = new_value;
newnode->next = NULL;
*root = newnode;
}
void printSLL(Node * root)
{
while(root != NULL)
{
printf("%d,", root->value);
root = root->next;
}
printf("\n");
}
void sllInsertSort(Node ** root)
{
Node * cur;
Node ** rootTrav = root, ** back ;
for ( ; (cur = *rootTrav) != NULL ; rootTrav = back)
{
back = &cur->next;
Node ** rootBak = root, *tmp;
while ((tmp = *rootBak) != cur && tmp->value < cur->value)
{
rootBak = &tmp->next;
}
if (tmp != cur)
{
*rootBak = cur;
if (root != rootBak)//insertion not on the first position
{
tmp->next = cur->next;
}
else
{
*rootTrav = cur->next;
}
cur->next = tmp;
}
}
}
int main()
{
Node * root = NULL;
insert(&root, 5);
insert(&root, 6);
insert(&root, 7);
insert(&root, 1);
printSLL(root);
sllInsertSort(&root);
printSLL(root);
return 0;
}
运行成功!!!
本文详细记录了一次在单向链表排序问题上的经历,从遇到问题到解决,包括算法实现、调试过程及最终成功运行的完整流程。通过实际案例,深入探讨了链表操作和排序算法的应用。
2696

被折叠的 条评论
为什么被折叠?



