DLinkList(雙鏈表)

#include<stdio.h>
typedef int Datatype;
typedef struct link_node {
Datatype info;
struct link_node *llink;
struct link_node *rlink;
}node;


node *init(node *head)
{
return NULL;
}


node *find_last(node *head)
{
node *pre = init(&pre), *p = head;
while (p)
{
pre = p;
p = p->rlink;
}
return pre;
}


void display(node *head)
{
if (!head)
printf("鏈表爲空,無法進行輸出!\n");
else
{
node *p = head;
while (p)
{
printf("%5d", p->info);
p = p->rlink;
}
}
}


void display_1(node *head)
{
if (!head)
printf("鏈表爲空,無法進行輸出!\n");
else
{
node *L;
L = find_last(head);
while (L)
{
printf("%5d", L->info);
L = L->llink;
}
}
}


node *find(node *head, int i)
{
node *p = head;
int j = 2;;
if (i == 1)
return head;
else
{
p = p->rlink;
while (p&&i != j)
{
p = p->rlink;
++j;
}
if (!p&&i != j)
{
printf("沒有找到第%d個結點\n", i);
return NULL;
}
else
if (i == j)
return p;
}
}


node *insert(node *head, Datatype x, int i)
{
node *p;
node *q = (node *)malloc(sizeof(node));
q->info = x;
q->llink = NULL;
q->rlink = NULL;
if (i == 0)
{
q->rlink = head;
head = q;
}
else
{
p = find(head, i);
if (p)
{
q->rlink = p->rlink;
q->llink = p;
p->rlink = q;
q->rlink->llink = q;
}
}
return head;
}


node *build(node *head, Datatype x)
{
node *p, *q;
p = (node *)malloc(sizeof(node));
p->info = x;
p->llink = NULL;
p->rlink = NULL;
if (head == NULL)
head = p;
else
{
q = find_last(head);
q->rlink = p;
p->llink = q;
}
return head;
}


node *dele(node *head, Datatype x)
{
node *p = head, *pre = init(&pre);
if (!p)
printf("鏈表爲空,無法進行刪除!\n");
else
{
while (p&&p->info != x)
{
pre = p;
p = p->rlink;
}
if (!p&&p->info != x)
printf("沒有找到要刪除的值!\n");
else
if (p->info == x)
{
pre->rlink = p->rlink;
p->rlink->llink = pre;
}
}
return head;
}


void main()
{
node *head;
head = init(&head);
int i;
node *f;
for (i = 0; i<10; i++)
head = build(head, i * 2);
display(head);
putchar('\n');
f = find(head, 8);
printf("第8個結點的值爲:%d\n", f->info);
head = insert(head, 666, 8);
printf("在第8個結點後插入一個值後鏈表爲:");
display(head);
putchar('\n');
head = dele(head, 8);
printf("刪除值爲8的結點後鏈表爲:");
display(head);
putchar('\n');
printf("逆序輸出鏈表各結點的值:");
display_1(head);
putchar('\n');
}
發佈了46 篇原創文章 · 獲贊 16 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章