【发布时间】:2014-01-27 14:37:26
【问题描述】:
好的。我有一个 c 编程课程的作业。 我需要实现一个函数原型:
void split(node* head, node **first, node **second)
该函数将head指向的双向链表拆分为两个列表first和second。
假设head 包含元素 F0,S0,F1,S1,F2,S2,...
然后:
-
first应按以下顺序包含元素:F0,F1,F2,... -
second应按以下顺序包含元素:S0,S1,S2,...
不要进行任何分配或释放(malloc、calloc、realloc、free)。只更新指针。不要更改节点数据。
限制:不要使用 malloc()、calloc()、realloc()、free()。
我卡住了,我无法生成任何算法。请帮忙!
typedef struct node
{
int data;
struct node *prev;
struct node *next;
} node;
编辑解决方案:
#define DATA(p) ((p)->data)
#define NEXT(p) ((p)->next)
#define PREV(p) ((p)->prev)
void split ( node* head, node **first, node **second )
{
node* firstCurrent = head;
node* secondCurrent = NULL;
node* dummyforbprev = NULL;
if ( firstCurrent )
{
secondCurrent = NEXT(firstCurrent);
if(secondCurrent)
PREV(secondCurrent)=NULL;
}
*first = firstCurrent;
*second = secondCurrent;
while ( firstCurrent && secondCurrent )
{
NEXT(firstCurrent) = NEXT(secondCurrent);
dummyforbprev = PREV(firstCurrent);
firstCurrent = NEXT(firstCurrent);
if(firstCurrent)
PREV(firstCurrent) = PREV(secondCurrent);
if ( firstCurrent )
NEXT(secondCurrent) = NEXT(firstCurrent);
PREV(secondCurrent) = dummyforbprev;
secondCurrent = NEXT(secondCurrent);
}
if ( firstCurrent )
NEXT(firstCurrent) = NULL;
if ( secondCurrent )
NEXT(secondCurrent) = NULL;
}
【问题讨论】:
-
显示您当前拥有的代码。
-
将 i 设置为 0。对于
head中的每个节点:从head中删除节点。如果 i 是偶数,则将节点附加到first的尾部,如果奇数,则将节点附加到second的尾部。递增 i 并循环。 -
@Magnus Reftel 如何删除和附加节点?你能解释一下吗?
-
@M Oehm 实际的问题是如何在不进行任何分配或释放的情况下做到这一点。不,这不一定。我已经实现了 delete_node() 和 insert_node() 函数。
-
你已经有了节点,所以你不需要克隆它来获得一个新的副本或任何东西。只需更改其
next和prev指针指向的内容(更新旧列表中的指针以匹配)。 en.wikipedia.org/wiki/Doubly_linked_list 有一个相当不错的解释
标签: c doubly-linked-list