【发布时间】:2016-02-06 18:00:06
【问题描述】:
我正在尝试对 C 中的列表进行合并排序。我看到了代码 here on French Wikipedia,但它给了我一个不正确的列表(即未排序)。该函数可以完美编译。请注意,我并没有真正使用top,我可能很快就会将其从结构中移除。你能帮我弄清楚这段代码有什么问题吗?我不得不将它从算法伪代码翻译成 C 代码。
谢谢。
P 是未排序的输入列表。
n 是列表的长度。
typedef struct s_stack t_stack;
struct s_stack {
int nbr;
int top;
struct s_stack *previous;
struct s_stack *next;
};
typedef t_stack *Pile;
t_stack *merge_sort(Pile p, int n) {
Pile q;
int Q;
int P;
q = NULL;
Q = n / 2;
P = n - Q;
if (P >= 2) {
q = merge_sort(p, P);
if (Q >= 2)
p = merge_sort(q, Q);
} else {
q = p->next;
}
q = fusion(p, P, q, Q);
return (q);
}
t_stack *fusion(Pile p, int P, Pile q, int Q) {
t_stack *tmp;
tmp = NULL;
while (1) {
if (p->next->nbr > q->next->nbr) {
/* my input list (not sorted) is circular and
I checked it is well linked ! This is the reason
why I need to do all that stuff with the nodes
It is basically supposed to move the node q->next
after node p */
tmp = q->next;
q->next = tmp->next;
q->next->previous = q;
tmp->previous = p;
tmp->next = p->next;
p->next->previous = tmp;
p->next = tmp;
if (Q == 1)
break;
Q = Q - 1;
} else {
if (P == 1) {
while (Q >= 1) {
q = q->next;
Q = Q - 1;
}
break;
}
P = P - 1;
}
p = p->next;
}
return (q);
}
【问题讨论】:
-
1.减少基本相同事物的名称数量。 2. 不要在 typedef 后面隐藏指针。 3. 记录
nbr和top的含义。本质上,数据结构应该是什么样子。 4. 两个辅助函数可能有用:splice和cut。 -
在 typedef 后面隐藏
*是一种非常糟糕的程序实践,可能/将会导致误解并使代码更难理解、调试和维护。
标签: c merge mergesort doubly-linked-list circular-list