昨天笔试,遇到一个单向链表排序的问题,感觉挺简单的,后来发现还是做错了。
今天在机器上调了半天终于调试成功了。
#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;
}
运行成功!!!