1、单向链表转换为双向循环链表
已知
struct lknode{
int data;
struct lknode *next;
}*lkhead;
lkhead是单向链表的头指针;
struct dbnode{
int data;
struct dbnode *prior, *next;
} *dbhead;
需实现的函数接口为struct *dbnode doublelist(struct lknode *lkhead);
已知
struct lknode{
int data;
struct lknode *next;
}*lkhead;
lkhead是单向链表的头指针;
struct dbnode{
int data;
struct dbnode *prior, *next;
} *dbhead;
需实现的函数接口为struct *dbnode doublelist(struct lknode *lkhead);
返回双向循环链表的头指针
struct *dbnode doublelist(struct lknode *lkhead)
{
struct lknode *p;
struct dbnode *pcurrentnode;
struct dbnode *pnewnode;
struct dbnode *pfirstnode;
struct dbnode *plastnode;
p = lkhead->next;
pfirstnode = (struct dbnode *)malloc(sizeof(struct dbnode));
pfirstnode->prior = NULL;
pfirstnode->data = (p->next)->data;
pcurrentnode = pfirstnode;
while(p!=NULL)
{
pnewnode = (struct dbnode *)malloc(sizeof(struct dbnode));
pcurrentnode->next = pnewnode;
pnewnode->data = p->data;
pnewnode->prior = pcurrentnode;
pcurrentnode = pnewnode;
p=p->next;
}
pcurrentnode->next=pfirstnode;
pfirstnode->prior = pcurrentnode;
return pfirstnode;
}
第二种方法:建立一个双向链表,然后往里面插节点
struct dbnode *pcurrent;
struct *dbnode doublelist(struct lknode *lkhead)
{
struct lknode *p;
struct dbnode *pfirstnode = (struct dbnode *)malloc(sizeof(struct dbnode));
pfirstnode->prior = pfirstnode;
pfirstnode->next = pfirstnode;
pfirstnode->data = lkhead->data;
pcurrent = pfirstnode;
while((p->next)!=NULL)
{
sll_insert(p->next->data);
p=p->next;
}
return pfirstnode;
}
void sll_insert(int new_value)
{
struct dbnode *pnewnode = (struct dbnode*)malloc(sizeof(struct dbnode));
pnewnode->prior = pcurrent;
pnewnode->data = new_value;
pnewnode->next = pfirstnode;
pcurrent = pnewnode;
}
PS:最近在看笔试题目,发现考的都不会。。。。