您的位置:首页 > 理论基础 > 数据结构算法

双链表基本操作

2014-06-17 16:29 302 查看
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define DNODE_SIZE sizeof(DNode)

typedef struct _tagDNode
{
int value;
struct _tagDNode *prov;
struct _tagDNode *next;
}DNode;

DNode* create_double_link(DNode *node)
{
DNode *head = NULL;
if (node->value == 0)
{
return head;
}

head = (DNode*)malloc(DNODE_SIZE);
head->value = node->value;
head->prov = NULL;
head->next = NULL;
return head;
}

DNode* insert2tail(DNode *head,DNode *node)
{
DNode *cur = head;
DNode *tn = NULL;

tn = (DNode*)malloc(DNODE_SIZE);
tn->value = node->value;

while (cur->next != NULL)
{
cur = cur->next;
}

cur->next = tn;
tn->prov = cur;
tn->next = NULL;
return head;
}

DNode* insert2head(DNode *head,DNode *node)
{
DNode *cur = head;
DNode *tn = NULL;

tn = (DNode*)malloc(DNODE_SIZE);
tn->value = node->value;

tn->prov = NULL;
tn->next = cur;
cur->prov = tn;

return tn;
}

DNode* insert(DNode *head,DNode *node)
{
DNode *cur = head;
DNode *tn = NULL;

tn = (DNode*)malloc(DNODE_SIZE);
tn->value = node->value;

if (cur->value >= node->value)
{
head = insert2head(head,node);
return head;
}

while (cur->next != NULL)
{
if (cur->value < node->value)
{
cur = cur->next;
continue;
}
break;
}

if ((cur ->next == NULL) && (cur->value <= node->value))
{
head = insert2tail(head,node);
return head;
}

tn->prov = cur->prov;
cur->prov->next = tn;
tn->next = cur;
cur->prov = tn;

return head;
}

void print_link_by_head(DNode *head)
{
DNode *tp = head;
while (tp->next != NULL)
{
printf("%d ",tp->value);
tp = tp->next;
}
printf("%d ",tp->value);
}

void print_link_by_tail(DNode *tail)
{
DNode *tp = tail;
while (tp->prov != NULL)
{
printf("%d ",tp->value);
tp = tp->prov;
}
printf("%d ",tp->value);
}

void delete_double_link(DNode *head)
{
DNode *cur = head;
DNode *prov= head;
while (cur->next != NULL)
{
prov = cur;
cur = cur->next;
free(prov);
}
free(cur);
cur = NULL;
prov = NULL;
}

DNode *gettail(DNode *head)
{
DNode *cur = head;
while (cur->next != NULL)
{
cur = cur->next;
}
return cur;
}
int main(void)
{
DNode *head = NULL;
DNode *tail = NULL;
DNode node = {0};
int i = 0;
node.value = 1;
head = create_double_link(&node);

node.value = 65;
head = insert(head,&node);

node.value = 3;
head = insert(head,&node);

node.value = 343;
head = insert(head,&node);

node.value = 33;
head = insert(head,&node);

node.value = 2;
head = insert(head,&node);

node.value = 99;
head = insert(head,&node);

print_link_by_head(head);
putchar('\n');
tail = gettail(head);
print_link_by_tail(tail);
putchar('\n');
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息